Home >Web Front-end >JS Tutorial >How Can I Convert an Array of Objects into a Single Object in JavaScript?

How Can I Convert an Array of Objects into a Single Object in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 09:48:12213browse

How Can I Convert an Array of Objects into a Single Object in JavaScript?

Converting an Array of Objects to a Single Object

In JavaScript, converting an array of objects into a single object can be achieved using object destructuring and the reduce() method. Consider the following array of objects:

[
  { key: '11', value: '1100' },
  { key: '22', value: '2200' }
]

Solution:

To convert this array into the desired object, follow these steps:

  1. Use the reduce() method to iterate over the array and accumulate the key-value pairs:
const object = arr.reduce((obj, item) => {
  return Object.assign(obj, { [item.key]: item.value });
}, {});
  1. The Object.assign() method merges the properties of the second object (in this case, { [item.key]: item.value }) into the first object (the obj accumulator).
  2. The initial value of obj is an empty object, so the first iteration creates the key property with the value stored in the item.key property. Similarly, the second iteration adds the 22 property with the value in item.value.
  3. The resulting object is assigned to the object variable.

Output:

Consuming the object variable will yield the desired output:

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

This solution effectively transforms the array of objects into a single object with the desired key-value pairs.

The above is the detailed content of How Can I Convert an Array of Objects into a Single Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn