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

How to Combine an Array of Objects into a Single Object in JavaScript?

DDD
Release: 2024-12-16 00:55:09
Original
734 people have browsed it

How to Combine an Array of Objects into a Single Object in JavaScript?

How to Transform an Array of Objects into a Consolidated Object in JavaScript

Converting an array of objects into a single consolidated object is a common task when working with complex data structures in JavaScript. One efficient way to achieve this is by leveraging the built-in reduce() method.

Implementation:

To transform an array of objects into a single object with key-value pairs, you can employ the following approach:

<br>var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}];</p>
<p>// Utilize reduce() to merge objects<br>var object = arr.reduce(<br>  (obj, item) => Object.assign(obj, { [item.key]: item.value }), {});</p>
<p>// Output the consolidated object<br>console.log(object);<br>

Output:

The code snippet above will generate the following consolidated object:

{
  "11": "1100",
  "22": "2200"
}
Copy after login

In this consolidated object, the key property of each array element serves as the keys for the object, while the value property becomes the corresponding values. The Object.assign() method is used to merge new properties into the object, effectively combining the data from all array elements into a single entity.

This method provides a concise and functional solution for converting arrays of objects into consolidated objects in JavaScript, ensuring efficient data manipulation and transformation.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template