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
Converting array of arrays into an object in JavaScript
Converting an array of arrays into an object is a common task in JavaScript when dealing with key-value pair data. This is particularly useful when transforming data from APIs or CSV-like structures.
Suppose we have an array of arrays that contains the performance of a cricket player like this:
const arr = [ ['Name', 'V Kohli'], ['Matches', 13], ['Runs', 590], ['Highest', 183], ['NO', 3], ['SR', 131.5] ];
We need to write a JavaScript function that takes such an array where each subarray represents one key-value pair. The first element is the key and the second is its value. The function should construct an object based on these pairs.
For the above array, the expected output should look like:
{
Name: 'V Kohli',
Matches: 13,
Runs: 590,
Highest: 183,
NO: 3,
SR: 131.5
}
Using For...of Loop
The most straightforward approach uses a for...of loop with array destructuring:
const arr = [
['Name', 'V Kohli'],
['Matches', 13],
['Runs', 590],
['Highest', 183],
['NO', 3],
['SR', 131.5]
];
const arrayToObject = (arr = []) => {
const res = {};
for (const pair of arr) {
const [key, value] = pair;
res[key] = value;
}
return res;
};
console.log(arrayToObject(arr));
{
Name: 'V Kohli',
Matches: 13,
Runs: 590,
Highest: 183,
NO: 3,
SR: 131.5
}
Using Object.fromEntries() (ES2019)
The modern and concise approach uses the built-in Object.fromEntries() method:
const arr = [ ['Name', 'V Kohli'], ['Matches', 13], ['Runs', 590], ['Highest', 183], ['NO', 3], ['SR', 131.5] ]; const result = Object.fromEntries(arr); console.log(result);
{
Name: 'V Kohli',
Matches: 13,
Runs: 590,
Highest: 183,
NO: 3,
SR: 131.5
}
Using reduce() Method
A functional programming approach using the reduce method:
const arr = [
['Name', 'V Kohli'],
['Matches', 13],
['Runs', 590],
['Highest', 183],
['NO', 3],
['SR', 131.5]
];
const arrayToObject = (arr) => {
return arr.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
};
console.log(arrayToObject(arr));
{
Name: 'V Kohli',
Matches: 13,
Runs: 590,
Highest: 183,
NO: 3,
SR: 131.5
}
Comparison
| Method | Browser Support | Readability | Performance |
|---|---|---|---|
| For...of Loop | ES2015+ | Good | Fast |
| Object.fromEntries() | ES2019+ | Excellent | Fast |
| reduce() | ES5+ | Good | Moderate |
Common Use Cases
This conversion pattern is useful for:
- Processing CSV data or form submissions
- Converting API responses to more usable formats
- Transforming configuration arrays into objects
Conclusion
Use Object.fromEntries() for modern browsers as it's the most concise. For broader compatibility, the for...of loop approach works reliably across all environments.
