JavaScript - Convert Two-Dimensional Array Into an Object
Last Updated :
11 Jan, 2025
Improve
Here are the different methods to convert the two-dimensional array into an object in JavaScript.
1. Using a for Loop
The simplest way to convert a two-dimensional array into an object is by iterating through the array using a for loop and assigning key-value pairs.
const a = [['name', 'Abhay'], ['age', 30], ['city', 'New Delhi']];
const obj = {};
for (let i = 0; i < a.length; i++) {
const [key, val] = a[i];
obj[key] = val;
}
console.log(obj);
Output
{ name: 'Abhay', age: 30, city: 'New Delhi' }
In this example
- The for loop iterates through the two-dimensional array a, destructuring each sub-array into a key and val, and assigns these as key-value pairs to the obj, effectively converting the array into an object.
2. Using reduce() Method
The reduce() method provides a clean, concise way to transform a two-dimensional array into an object in a single operation.
const a = [['name', 'Jaya'], ['age', 30], ['city', 'New Delhi']];
const obj = a.reduce((acc, [key, val]) => {
acc[key] = val;
return acc;
}, {});
console.log(obj);
Output
{ name: 'Jaya', age: 30, city: 'New Delhi' }
In this example
- The reduce() method processes each sub-array in a, destructuring it into key and val, and adds them as properties to the acc object.
- The final accumulated object, obj, contains all key-value pairs from the two-dimensional array.
3. Using Object.fromEntries()
With the introduction of Object.fromEntries() in ES2019, converting a two-dimensional array into an object has become straightforward and efficient.
const a = [['name', 'Joy'],['age', 30],['city', 'New Delhi']];
const obj = Object.fromEntries(a);
console.log(obj);
Output
{ name: 'Joy', age: 30, city: 'New Delhi' }
In this example :
- The Object.fromEntries() method directly converts the two-dimensional array a into an object by treating each sub-array as a [key, value] pair.
- The resulting object, obj, contains the key-value pairs extracted from the array.
Comparison and Use Cases
Approach | When to Use |
---|---|
for loop | Basic and widely supported, useful for beginners. |
reduce | When functional programming style is preferred. |
Object.fromEntries() | For modern JavaScript, concise, and easy to read. |
By selecting the appropriate approach, you can effectively convert a two-dimensional array into an object based on your requirements.