Angular update object in object array
Say i have the following object array, lets name it itemArray;
{
"totalItems": 2,
"items": [
{
"id": 1,
"name": "foo"
},
{
"id": 2,
"name": "bar"
},
]
}
And i have a subscription that returns the updated result of only id 2. How would i update the object array without looping through the entire array?
What i would like is something like the example below;
updateUser(user){
this.myservice.getUpdate(user.id)
.subscribe(newitem => {
this.updateArray(newitem);
});
}
updateArray(newitem){
this.itemArray.items[newitem.id].name = newitem.name
}
or even better, replacing the entire object;
updateArray(newitem){
this.itemArray.items[newitem.id] = newitem
}
This example however updates the array based on the index of the array. So how do i instead update based on newitem.id?
Template requested in comment:
<tr *ngFor="let u of itemsArray.items; let i = index">
<td>{{ u.id }}</td>
<td>{{ u.name }}</td>
<td>
<input type="checkbox" checked="u.accepted" [(ngModel)]="itemsArray.items[i].accepted" (ngModelChange)="updateUser(u)">
<label for="singleCheckbox-{{i}}"></label>
</td>
</tr>
Solution 1:
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.
Solution 2:
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;
Solution 3:
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;
Solution 4:
You can try this also to replace existing object
toDoTaskList = [
{id:'abcd', name:'test'},
{id:'abcdc', name:'test'},
{id:'abcdtr', name:'test'}
];
newRecordToUpdate = {id:'abcdc', name:'xyz'};
this.toDoTaskList.map((todo, i) => {
if (todo.id == newRecordToUpdate .id){
this.toDoTaskList[i] = updatedVal;
}
});