Sometimes, we want to convert array of objects into one object in JavaScript.
In this article, we’ll look at how to convert array of objects into one object in JavaScript.
How to convert array of objects into one object in JavaScript?
To convert array of objects into one object in JavaScript, we can use the array reduce method.
For instance, we write
const arr = [
{ key: "11", value: "1100" },
{ key: "22", value: "2200" },
];
const object = arr.reduce(
(obj, item) => Object.assign(obj, { [item.key]: item.value }),
{}
);
console.log(object);
to call arr.reduce with a callback that calls Object.assign with obj and an object with the property that we want to add to obj and return it.
The 2nd argument is an empty object so obj‘s initial value is an empty object.
Conclusion
To convert array of objects into one object in JavaScript, we can use the array reduce method.