修改对象数组中的对象属性 [英] 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);
有没有办法在不创建新数组的情况下修改某个对象属性(就像我上面过滤的那个)和/或对象?
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?
所需结果: [{bar:1,baz:[11,22,33]},{bar:2 ,baz:[4,5,6]}]
推荐答案
当然,只需更改它:
使用jQuery的 $。每个
:
$.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];`
}
});
ES5的 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];`
}
});
...或者你有其他SO回答中的其他循环选项。
这篇关于修改对象数组中的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文