Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert JS array into an object - JavaScript
Converting a JavaScript array into an object is a common task in web development. This article shows different approaches to transform an array of objects into a single object using various JavaScript methods.
Suppose we have an array of objects like this:
const arr = [
{id: 1, name: "Mohan"},
{id: 2, name: "Sohan"},
{id: 3, name: "Rohan"}
];
console.log("Input array:", arr);
Input array: [
{ id: 1, name: 'Mohan' },
{ id: 2, name: 'Sohan' },
{ id: 3, name: 'Rohan' }
]
We need to create an object where each id becomes a key, and the corresponding name becomes the value within a nested object.
Method 1: Using for Loop
The traditional approach uses a for loop to iterate through the array:
const arr = [
{id: 1, name: "Mohan"},
{id: 2, name: "Sohan"},
{id: 3, name: "Rohan"}
];
const arrayToObject = arr => {
const res = {};
for(let ind = 0; ind
{
'1': { name: 'Mohan' },
'2': { name: 'Sohan' },
'3': { name: 'Rohan' }
}
Method 2: Using reduce()
The reduce() method provides a more functional approach:
const arr = [
{id: 1, name: "Mohan"},
{id: 2, name: "Sohan"},
{id: 3, name: "Rohan"}
];
const arrayToObjectReduce = arr => {
return arr.reduce((acc, item) => {
acc[item.id] = { name: item.name };
return acc;
}, {});
};
console.log(arrayToObjectReduce(arr));
{
'1': { name: 'Mohan' },
'2': { name: 'Sohan' },
'3': { name: 'Rohan' }
}
Method 3: Using Object.fromEntries()
For a more modern approach, combine map() with Object.fromEntries():
const arr = [
{id: 1, name: "Mohan"},
{id: 2, name: "Sohan"},
{id: 3, name: "Rohan"}
];
const arrayToObjectEntries = arr => {
return Object.fromEntries(
arr.map(item => [item.id, { name: item.name }])
);
};
console.log(arrayToObjectEntries(arr));
{
'1': { name: 'Mohan' },
'2': { name: 'Sohan' },
'3': { name: 'Rohan' }
}
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| for loop | Good | Fastest | All browsers |
| reduce() | Very good | Good | ES5+ |
| Object.fromEntries() | Excellent | Good | ES2019+ |
Conclusion
All three methods effectively convert arrays to objects. Use reduce() for functional programming style, or Object.fromEntries() for the most modern and readable approach. The for loop remains the fastest option for performance-critical applications.
