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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 08:17:02446browse

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!

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