Tuesday, 18 January 2022

JS findIndex of array

 You can use findIndex to find the index in the array of the object and replace it as required:

var item = {...}
var items = [{id:2}, {id:2}, {id:2}];

var foundIndex = items.findIndex(x => x.id == item.id);
items[foundIndex] = item;

This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:

items.forEach((element, index) => {
    if(element.id === item.id) {
        items[index] = item;
    }
});
https://stackoverflow.com/questions/35206125/how-can-i-find-and-update-values-in-an-array-of-objects

No comments:

Post a Comment