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" }
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!