Flatten array with objects into 1 object

前端 未结 8 1500
情歌与酒
情歌与酒 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:15

    Here is a nice usage of Object.assign with the array.prototype.reduce function:

    let merged = arrOfObjs.reduce((accum, val) => {
      Object.assign(accum, val);
      return accum;
    }, {})
    

    This approach does not mutate the input array of objects, which could help you avoid difficult to troubleshoot problems.

提交回复
热议问题