Home >Web Front-end >JS Tutorial >How do I convert an array of objects to a single object with key-value pairs in JavaScript?
In JavaScript, converting an array of objects to a single object with key-value pairs requires the use of advanced array manipulation techniques. Let's explore how to achieve this in a browser-compatible way.
To start, let's understand the structure of the input array:
This array contains multiple objects, each with one key-value pair. Our goal is to create an object that merges the key-value pairs from all objects in the array.
The most modern and browser-compatible solution is to use the Object.assign() method along with the spread syntax (...). Object.assign() merges properties from multiple source objects into a target object. Using a spread syntax on the arr array allows us to flatten it, merging all objects into a single source.
In this example, Object.assign() creates a new object (object) by merging an empty object {} with the flattened array created by the spread syntax (...array). This combines all key-value pairs from the objects in the arr array into a single object.
If you need to support legacy browsers that do not have Object.assign() or spread syntax, you can use a polyfill to provide these methods. Additionally, there are other alternative methods, such as using reduce() or for loops, to achieve the same result. However, these approaches may be less efficient or require more code.
The above is the detailed content of How do I convert an array of objects to a single object with key-value pairs in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!