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 };
0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Needlessly verbose. Instead, use Object.assign({}, ...arr)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.