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 };
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 };
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);
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).