Home > Article > Web Front-end > How to Convert an Array of Objects to a Key-Value Object in JavaScript?
Array to Key-Value Object Conversion in JavaScript
To convert an array of objects to an object with key-value pairs, JavaScript provides a simple and effective solution. This is especially useful when dealing with data manipulation.
Array Declaration
Let's assume we have an array of objects like this:
var arr = [{ name1: "value1" }, { name2: "value2" }, ...];
Object Creation
To convert this array into an object, we can utilize Object.assign and the spread syntax (...). The Object.assign method creates a new object by combining the properties from one or more source objects.
The following code snippet demonstrates how to perform the conversion:
var object = Object.assign({}, ...array);
In this example, the spread syntax (...) creates a copy of each object in the array. These copies are then passed as arguments to Object.assign, ensuring that the properties from each object are merged into the new object.
Output
The resulting object will have the desired key-value pair structure:
{ name1: "value1", name2: "value2", ... }
Browser Compatibility
This approach is supported in a wide range of browsers, including modern versions of Chrome, Firefox, Safari, and Edge. It also works in Node.js environments.
The above is the detailed content of How to Convert an Array of Objects to a Key-Value Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!