Javascript ES6/ES5 find in array and change

前端 未结 8 1330
后悔当初
后悔当初 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:03

    Whereas most of the existing answers are great, I would like to include an answer using a traditional for loop, which should also be considered here. The OP requests an answer which is ES5/ES6 compatible, and the traditional for loop applies :)

    The problem with using array functions in this scenario, is that they don't mutate objects, but in this case, mutation is a requirement. The performance gain of using a traditional for loop is just a (huge) bonus.

    const findThis = 2;
    const items = [{id:1, ...}, {id:2, ...}, {id:3, ...}];
    
    for (let i = 0, l = items.length; i < l; ++i) {
      if (items[i].id === findThis) {
        items[i].iAmChanged = true;
        break;
      }
    }
    

    Although I am a great fan of array functions, don't let them be the only tool in your toolbox. If the purpose is mutating the array, they are not the best fit.

提交回复
热议问题