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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 14:03:02346browse

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"},...]

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

{"name1":"value1","name2":"value2",...}

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);

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!

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