Home >Web Front-end >JS Tutorial >How to Convert an Array of Objects to a Single Key-Value Pair Object in JavaScript?
Converting an Array of Objects to an Object with Key-Value Pairs
Question:
How can you transform an array of objects into a single object with key-value pairs in JavaScript?
Support Requirement:
The solution should be compatible with a wide range of browsers.
Answer:
To effectively merge an array of objects into a single object, utilize Object.assign() in conjunction with spread syntax (...). This technique allows you to create a new object with the merged properties from the original array. Consider the following code snippet:
var array = [{ name1: "value1" }, { name2: "value2" }] var object = Object.assign({}, ...array) console.log(object)
This code creates an object object by spread-expanding the array array and merging its properties into an empty object {} using Object.assign(). The console.log() statement prints the resulting object object, which contains key-value pairs extracted from the original array.
The above is the detailed content of How to Convert an Array of Objects to a Single Key-Value Pair Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!