Categories
JavaScript Answers

How to Flatten an Array with Objects into 1 Object with JavaScript?

Spread the love

To flatten an array with objects into 1 object with JavaScript, we can use the Object.assign method with the spread operator.

For instance, we write:

const arr = [{ a: 1 }, { b: 2 }, { c: 3 }]
const merged = Object.assign(...arr);
console.log(merged)

We have the arr array with multiple objects inside.

Then we call Object.assign with all the arr entries as arguments by spreading them into the Object.assign method.

It returns an object with the properties of all the objects merged in.

This is then assigned to merged.

Therefore, merged is:

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *