Modify object property in an array of objects
You can use find
and change its property.
let foo = [{ bar: 1, baz: [1,2,3] }, { bar: 2, baz: [4,5,6] }];
let obj = foo.find(f=>f.bar==1);
if(obj)
obj.baz=[2,3,4];
console.log(foo);
.map
with spread (...
) operator
var result = foo.map(el => el.bar == 1 ? {...el, baz: [11,22,33]} : el);
Sure, just change it:
With jQuery's $.each
:
$.each(foo, function() {
if (this.bar === 1) {
this.baz[0] = 11;
this.baz[1] = 22;
this.baz[2] = 33;
// Or: `this.baz = [11, 22, 33];`
}
});
With ES5's forEach
:
foo.forEach(function(obj) {
if (obj.bar === 1) {
obj.baz[0] = 11;
obj.baz[1] = 22;
obj.baz[2] = 33;
// Or: `obj.baz = [11, 22, 33];`
}
});
...or you have other looping options in this other SO answer.