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

Sometimes, we want to flatten an array with objects into 1 object with JavaScript.

In this article, we’ll look at how to flatten an array with objects into 1 object with JavaScript.

Flatten an Array with Objects into 1 Object with JavaScript

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
}

Conclusion

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