How to Convert an Array of Objects into One Object in JavaScript?

Sumit kumar Singh
3 min readMar 28, 2023

To convert an array of objects into one object in JavaScript, you can use various methods depending on your requirements. Here are a few approaches you can take:

Approach 1: Using Object.assign() method

The Object.assign() method can be used to combine objects into a single object. It takes one or more source objects and combines them into a target object. Here is an example of how to use this method to convert an array of objects into one object:

const arr = [{ key1: 'value1' }, { key2: 'value2' }, { key3: 'value3' }];

const result = Object.assign({}, ...arr);

console.log(result); // { key1: 'value1', key2: 'value2', key3: 'value3' }

In this example, the spread operator ... is used to pass the array of objects as separate arguments to the Object.assign() method. The empty object literal {} is used as the target object. The method then combines all objects in the array into a single object, which is assigned to the result variable.

Approach 2: Using the reduce() method

Another approach is to use the reduce() method to iterate over the array and combine the objects into a single object. Here is an example:

const arr = [{ key1…

--

--

Sumit kumar Singh
Sumit kumar Singh

Written by Sumit kumar Singh

YouTube: https://shorturl.at/8zZ4B Linkedin: https://shorturl.at/TeLw7 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks on Web Development

Responses (1)