Home >Web Front-end >JS Tutorial >How to Convert an Array of Objects to a Single Key-Value Pair Object in JavaScript?

How to Convert an Array of Objects to a Single Key-Value Pair Object in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 09:38:01275browse

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!

Statement:
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