Modify object property in an array of objects
var foo = [{ bar: 1, baz: [1,2,3] }, { bar: 2, baz: [4,5,6] }];
var filtered = $.grep(foo, function(v){
return v.bar === 1;
});
console.log(filtered);
http://jsfiddle.net/98EsQ/
Is there any way to modify a certain objects property (like the one I'm filtering out above) without creating new arrays and/or objects?
Desired result: [{ bar: 1, baz: [11,22,33] }, { bar: 2, baz: [4,5,6] }]
.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.
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);
Without jQuery and backwards compatibility
for (var i = 0; i < foo.length; i++) {
if (foo[i].bar === 1) {
foo[i].baz = [11,12,13];
}
}
We can also achieve this by using Array's map function:
foo.map((obj) => {
if(obj.bar == 1){
obj.baz[0] = 11;
obj.baz[1] = 22;
obj.baz[2] = 33;
}
})