Modify object property in an array of objects

后端 未结 11 1118
抹茶落季
抹茶落季 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:44

    You can modify the array by using simple for loop

    var foo = [{ bar: 1, baz: [1,2,3] }, { bar: 2, baz: [4,5,6] }];
    for(i = 0;i < foo.length;i++){
      //Here your confition for which item you went to edit
    	if(foo[i].bar == 1){
        //Here you logic for update property
    		foo[i].baz= [1,11,22]
    	}
    }
    console.log(foo);

    0 讨论(0)
  • 2020-11-29 07:45

    .map with spread (...) operator

    var result = foo.map(el => el.bar == 1 ? {...el, baz: [11,22,33]} : el);

    0 讨论(0)
  • 2020-11-29 07:51

    But before opting any of the mentioned techniques please keep in mind the performance challenges associated with each of the approach.

    Object iterate For-In, average: ~240 microseconds.
    
    Object iterate Keys For Each, average: ~294 microseconds.
    
    Object iterate Entries For-Of, average: ~535 microseconds.
    

    Reference - 3 JavaScript Performance Mistakes You Should Stop Doing

    0 讨论(0)
  • 2020-11-29 07:55
        const objArr = [
            {prop1: 'value1', prop2: 'value11'},
            {prop1: 'value2', prop2: 'value22'},
            {prop1: 'value3', prop2: 'option33'},
            {prop1: 'value4', prop2: 'option44'}
        ]
    
        const newObjArr = objArr.map(obj => {
                if (['value1', 'value2'].includes(obj.prop1)) {
                    return {...obj, prop1: 'newValue'}
                }
                return obj
            }
        )
        
        // const responseGotten = [
        //     { prop1: 'newValue', prop2: 'value11' },
        //     { prop1: 'newValue', prop2: 'value22' },
        //     { prop1: 'value3', prop2: 'option33' },
        //     { prop1: 'value4', prop2: 'option44' }
        // ]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题