Angular update object in object array
Another approach could be:
let myList = [{id:'aaa1', name: 'aaa'}, {id:'bbb2', name: 'bbb'}, {id:'ccc3', name: 'ccc'}];
let itemUpdated = {id: 'aaa1', name: 'Another approach'};
myList.find(item => item.id == itemUpdated.id).name = itemUpdated.name;
I have created this Plunker based on your example that updates the object equal to newItem.id
Here's the snippet of my functions:
showUpdatedItem(newItem){
let updateItem = this.itemArray.items.find(this.findIndexToUpdate, newItem.id);
let index = this.itemArray.items.indexOf(updateItem);
this.itemArray.items[index] = newItem;
}
findIndexToUpdate(newItem) {
return newItem.id === this;
}
Hope this helps.
Updating directly the item passed as argument should do the job, but I am maybe missing something here ?
updateItem(item){
this.itemService.getUpdate(item.id)
.subscribe(updatedItem => {
item = updatedItem;
});
}
EDIT : If you really have no choice but to loop through your entire array to update your item, use findIndex :
let itemIndex = this.items.findIndex(item => item.id == retrievedItem.id);
this.items[itemIndex] = retrievedItem;