Home  >  Article  >  Web Front-end  >  How do I convert an array of objects to a single object with key-value pairs in JavaScript?

How do I convert an array of objects to a single object with key-value pairs in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 11:03:02866browse

How do I convert an array of objects to a single object with key-value pairs in JavaScript?

Converting an Array of Objects to an 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.

Using Object.assign() and Spread Syntax

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.

Support for Older Browsers

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!

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