0

How to merge objects in an array with ES6 spread operator? Let's say we have objects like this:

    let arr = [{ a: 1, b: true }, { c: "val", d: null }];

and this object as an result:

    { a: 1, b: true, c: "val", d: null };
mcs_dodo
  • 738
  • 1
  • 10
  • 17

2 Answers2

3

You could spread the elements into an Object.assign, without further looping.

let arr = [{ a: 1, b: true }, { c: "val", d: null }],
    result = Object.assign({}, ...arr);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

There is Array.prototype.reduce() function (docs here).

let arr = [{ a: 1, b: true }, { c: "val", d: null }];
let obj = arr.reduce((accumulator, current) => ({...accumulator, ...current}), {});
console.log(obj);

As always, with returning object literals from arrow function, don't forget to wrap return value with paremtheses (...) like this ({...accumulator, ...current}) in order to distinguish between code block and object literal (docs here).

mcs_dodo
  • 738
  • 1
  • 10
  • 17