Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-11-08 09:38:01
Original
194 people have browsed it

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!