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

How to Convert an Array of Objects into a Single Object with Key Value Pairs in JavaScript?

Patricia Arquette
Release: 2024-11-10 14:03:02
Original
275 people have browsed it

How to Convert an Array of Objects into a Single Object with Key Value Pairs in JavaScript?

Converting Array of Objects to Object with Key Value Pairs

Given an array of objects like:

arr = [{"name1":"value1"},{"name2":"value2"},...]
Copy after login

How can it be converted to a single object with key-value pairs:

{"name1":"value1","name2":"value2",...}
Copy after login

This conversion is commonly needed for various programming scenarios. Below is a solution that is compatible with a wide range of browsers:

Solution:

Using a combination of Object.assign and the spread operator:

var object = Object.assign({}, ...arr);
Copy after login

Explanation:

Object.assign() merges multiple source objects into a target object. The ...arr syntax uses the spread operator to concatenate all objects in the array into a single object. Therefore, the result is a new object that contains all key-value pairs from all objects in the array.

Note:

This solution is supported in all major browsers that support ES6, including Chrome, Firefox, Edge, and Safari.

The above is the detailed content of How to Convert an Array of Objects into a Single Object with Key Value Pairs 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