Add key value pair to all objects in array

后端 未结 10 1905
醉酒成梦
醉酒成梦 2020-12-04 10:43

I wanted to add a key:value parameter to all the objects in an array.

eg:

var arrOfObj = [{name: \'eve\'},{name:\'john\'},{name:\'jane\'}];
<         


        
10条回答
  •  执念已碎
    2020-12-04 11:31

    I would be a little cautious with some of the answers presented in here, the following examples outputs differently according with the approach:

    const list = [ { a : 'a', b : 'b' } , { a : 'a2' , b : 'b2' }]
    
    console.log(list.map(item => item.c = 'c'))
    // [ 'c', 'c' ]
    
    console.log(list.map(item => {item.c = 'c'; return item;}))
    // [ { a: 'a', b: 'b', c: 'c' }, { a: 'a2', b: 'b2', c: 'c' } ]
    
    console.log(list.map(item => Object.assign({}, item, { c : 'c'})))
    // [ { a: 'a', b: 'b', c: 'c' }, { a: 'a2', b: 'b2', c: 'c' } ]
    

    I have used node v8.10.0 to test the above pieces of code.

提交回复
热议问题