Modify object property in an array of objects

后端 未结 11 1167
抹茶落季
抹茶落季 2020-11-29 07:09
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);
<         


        
11条回答
  •  攒了一身酷
    2020-11-29 07:57

    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.

提交回复
热议问题