Categories
JavaScript Answers

How to Convert an Array of Objects into One Object in JavaScript?

Spread the love

We can use the JavaScript array reduce method to combine objects in an array into one object.

For instance, we can write:

const arr = [{
  key: "11",
  value: "1100"
}, {
  key: "22",
  value: "2200"
}];
const object = arr.reduce((obj, item) => ({
  ...obj,
  [item.key]: item.value
}), {});
console.log(object)

We have the arr array which we want to combine into one object.

To do that, we call reduce with a callback that returns an object with obj spread into the returned object.

And we add the item.key property with itemn.value as its value.

Therefore, object is:

{11: "1100", 22: "2200"}

Use the Array.prototype.map and Object.assign Methods

Another way to combine an array of objects into one object is to map each entry into their own object.

Then we can combine them all into one with Object.assign .

For instance, we can write:

const arr = [{
  key: "11",
  value: "1100"
}, {
  key: "22",
  value: "2200"
}];
const mapped = arr.map(item => ({
  [item.key]: item.value
}));
const object = Object.assign({}, ...mapped);
console.log(object)

We call map with a callback that returns an object the key and value of the object.

Then we spread mapped into Object.assign as arguments to add the properties in the mapped objects into the empty object.

Therefore, object has the same value as the previous example.

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 *