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
}