简体   繁体   中英

Updating observable array in knockout

I have an observable array named administrators. I also have an object named adminToAdd. AdminToAdd contains a single item with the exact same properties as administrators. I'm able to push adminToAdd into administrators with no issue.

Unfortunately, I'm unable update an existing item in administrators. I'm receiving the item to update in adminToAdd. I've tried

vm.administrators.replace(vm.administrators.indexOf(vm.adminToAdd), vm.adminToAdd);

but although the structure is the same between them the index won't match. I've looked at several examples but none seem to work for my scenario. Any ideas?

The reason why your approach doesn't work is because when you use indexOf in trying to find an object rather than a value. When finding an object it uses the memory addresses to decide equality rather than the values of the object.

I love ko's utility function ko.utils.arrayFirst(array, predicate) for situations like these. This allows you to search for a specific item within an array and return it if found. You provide a predicate function that will return true in the event that the object is equal or false for anything else.

var existingItem = ko.utils.arrayFirst(vm.administrators(), function (item) { 
    return <true or false statement> //define what constitutes equal here; 
});

if (existingItem) {
    vm.administrators.remove(existingItem);
    vm.administrators.push(vm.adminToAdd());
}
else {
   //case where it wasn't in the array 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM