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!