Javascript ES6/ES5 find in array and change

前端 未结 8 1320
后悔当初
后悔当初 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条回答
  •  Happy的楠姐
    2020-12-12 10:59

    An other approach is to use splice.

    The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

    N.B : In case you're working with reactive frameworks, it will update the "view", your array "knowing" you've updated it.

    Answer :

    var item = {...}
    var items = [{id:2}, {id:2}, {id:2}];
    
    let foundIndex = items.findIndex(element => element.id === item.id)
    items.splice(foundIndex, 1, item)
    

    And in case you want to only change a value of an item, you can use find function :

    // Retrieve item and assign ref to updatedItem
    let updatedItem = items.find((element) => { return element.id === item.id })
    
    // Modify object property
    updatedItem.aProp = ds.aProp
    

提交回复
热议问题