Home >Web Front-end >JS Tutorial >How Can I Convert an Array of Objects into a Single Object in JavaScript?
Converting an Array of Objects to a Single Object
In JavaScript, converting an array of objects into a single object can be achieved using object destructuring and the reduce() method. Consider the following array of objects:
[ { key: '11', value: '1100' }, { key: '22', value: '2200' } ]
Solution:
To convert this array into the desired object, follow these steps:
const object = arr.reduce((obj, item) => { return Object.assign(obj, { [item.key]: item.value }); }, {});
Output:
Consuming the object variable will yield the desired output:
{ "11": "1100", "22": "2200" }
This solution effectively transforms the array of objects into a single object with the desired key-value pairs.
The above is the detailed content of How Can I Convert an Array of Objects into a Single Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!