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 = items.find(x => x.id == item.id);
foundItem = item;
I want it to change the original object. How? (I dont care if it will be in lodash too)
You can use findIndex to find the index in the array of the object and replace it as required:
This assumes unique IDs. If your IDs are duplicated (as in your example), it's probably better if you use forEach:
One-liner using spread operator.
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.
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.
Given a changed object and an array:
Update the array with the new object by iterating over the array:
worked for me
My best approach is:
Reference for findIndex
And in case you don't want to replace with new object, but instead to copy the fields of
item
, you can useObject.assign
:Object.assign(items[items.findIndex(el => el.id === item.id)], item)
as an alternative with
.map()
:Object.assign(items, items.map(el=> el.id === item.id? item : el))