Flatten array with objects into 1 object

前端 未结 8 1499
情歌与酒
情歌与酒 2020-12-03 09:41

Given input:

[{ a: 1 }, { b: 2 }, { c: 3 }]

How to return:

{ a: 1, b: 2, c: 3 }

For arrays it\'s not a pr

8条回答
  •  情深已故
    2020-12-03 10:40

    With lodash, you can use merge():

    var arr = [ { a: 1 }, { b: 2 }, { c: 3 } ];
    _.merge.apply(null, [{}].concat(arr));
    // → { a: 1, b: 2, c: 3 }
    

    If you're doing this in several places, you can make merge() a little more elegant by using partial() and spread():

    var merge = _.spread(_.partial(_.merge, {}));
    merge(arr);
    // → { a: 1, b: 2, c: 3 }
    

提交回复
热议问题