Javascript ES6/ES5 find in array and change

前端 未结 8 1289
后悔当初
后悔当初 2020-12-12 10:52

I have an array of objects. I want to find by some field, and then to change it:

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

var foundItem = item         


        
相关标签:
8条回答
  • 2020-12-12 11:14

    Given a changed object and an array:

    const item = {...}
    let items = [{id:2}, {id:3}, {id:4}];
    

    Update the array with the new object by iterating over the array:

    items = items.map(x => (x.id === item.id) ? item : x)
    
    0 讨论(0)
  • 2020-12-12 11:20

    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;
        }
    });
    
    0 讨论(0)
提交回复
热议问题