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);
有没有办法修改某些对象属性(像我上面过滤掉的那样),而不创建新的数组和/或对象?
所需结果:[{bar:1,baz:[11,22,33]},{bar:2,baz:[4,6]}]
解决方法
当然,只是改变它:
用jQuery的$.each:
$.each(foo,function() { if (this.bar === 1) { this.baz[0] = 11; this.baz[1] = 22; this.baz[2] = 33; } });
与ES5的forEach:
foo.forEach(function(obj) { if (obj.bar === 1) { obj.baz[0] = 11; obj.baz[1] = 22; obj.baz[2] = 33; } });