Imagine having a unique object array named itemArray with two items inside;
{
"totalItems": 2,
"items": [
{
"id": 1,
"name": "dog"
},
{
"id": 2,
"name": "cat"
},
]
}
If you receive an updated result for only id 2 through a subscription, how can you efficiently update the object array without looping through all items?
An ideal solution would be something like the following code snippet;
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, completely replacing the entire object;
updateArray(newitem){
this.itemArray.items[newitem.id] = newitem
}
The provided example updates the array based on the index of the array. How can you instead update it 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>