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 2D array to object using map or reduce in JavaScript
Converting a 2D array to an object is a common task in JavaScript. Let's say we have a two-dimensional array that contains data about people's ages.
The data is given by the following 2D array:
const data = [ ['Rahul', 23], ['Vikky', 27], ['Sanjay', 29], ['Jay', 19], ['Dinesh', 21], ['Sandeep', 45], ['Umesh', 32], ['Rohit', 28], ]; console.log(data);
[ [ 'Rahul', 23 ], [ 'Vikky', 27 ], [ 'Sanjay', 29 ], [ 'Jay', 19 ], [ 'Dinesh', 21 ], [ 'Sandeep', 45 ], [ 'Umesh', 32 ], [ 'Rohit', 28 ] ]
We need to convert this array into an object where the first element of each subarray becomes the key and the second element becomes the value.
Using Array.reduce() Method
The reduce() method is ideal for transforming arrays into objects. It accumulates values into a single result:
const data = [
['Rahul', 23],
['Vikky', 27],
['Sanjay', 29],
['Jay', 19],
['Dinesh', 21],
['Sandeep', 45],
['Umesh', 32],
['Rohit', 28],
];
const constructObject = arr => {
return arr.reduce((acc, val) => {
const [key, value] = val;
acc[key] = value;
return acc;
}, {});
};
console.log(constructObject(data));
{
Rahul: 23,
Vikky: 27,
Sanjay: 29,
Jay: 19,
Dinesh: 21,
Sandeep: 45,
Umesh: 32,
Rohit: 28
}
Using Object.fromEntries() Method
A more concise approach uses Object.fromEntries(), which directly converts key-value pairs into an object:
const data = [ ['Rahul', 23], ['Vikky', 27], ['Sanjay', 29], ['Jay', 19] ]; const result = Object.fromEntries(data); console.log(result);
{ Rahul: 23, Vikky: 27, Sanjay: 29, Jay: 19 }
Using Array.map() with Spread Operator
You can also use map() combined with Object.assign() and the spread operator:
const data = [
['Rahul', 23],
['Vikky', 27],
['Sanjay', 29]
];
const result = Object.assign({}, ...data.map(([key, value]) => ({ [key]: value })));
console.log(result);
{ Rahul: 23, Vikky: 27, Sanjay: 29 }
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
Array.reduce() |
Good | Fast | Excellent |
Object.fromEntries() |
Excellent | Fast | ES2019+ |
map() + spread |
Medium | Slower | ES6+ |
Conclusion
Use Object.fromEntries() for the cleanest code in modern environments, or Array.reduce() for better browser compatibility. Both methods efficiently convert 2D arrays to objects.
