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 object to 2-D array in JavaScript
In JavaScript, we often need to convert objects into 2D arrays where each sub-array contains a key-value pair. This is useful for data processing, iteration, or when working with APIs that expect array formats.
Suppose we have an object that contains information about the weather of a city:
const obj = {
city: "New Delhi",
maxTemp: 32,
minTemp: 21,
humidity: 78,
aqi: 456,
day: 'Tuesday',
};
We need to convert this object into a 2D array where each sub-array contains exactly two elements:
the corresponding key
that key's value
The expected output should look like:
[ [ 'city', 'New Delhi' ], [ 'maxTemp', 32 ], [ 'minTemp', 21 ], [ 'humidity', 78 ], [ 'aqi', 456 ], [ 'day', 'Tuesday' ] ]
Method 1: Using Object.keys() and Loop
const obj = {
city: "New Delhi",
maxTemp: 32,
minTemp: 21,
humidity: 78,
aqi: 456,
day: 'Tuesday',
};
const objectToArray = (obj = {}) => {
const res = [];
const keys = Object.keys(obj);
for(key of keys){
res.push([
key, obj[key]
]);
};
return res;
};
console.log(objectToArray(obj));
[ [ 'city', 'New Delhi' ], [ 'maxTemp', 32 ], [ 'minTemp', 21 ], [ 'humidity', 78 ], [ 'aqi', 456 ], [ 'day', 'Tuesday' ] ]
Method 2: Using Object.entries() (Recommended)
JavaScript provides a built-in method Object.entries() that directly converts an object to an array of key-value pairs:
const obj = {
city: "New Delhi",
maxTemp: 32,
minTemp: 21,
humidity: 78,
aqi: 456,
day: 'Tuesday',
};
const result = Object.entries(obj);
console.log(result);
[ [ 'city', 'New Delhi' ], [ 'maxTemp', 32 ], [ 'minTemp', 21 ], [ 'humidity', 78 ], [ 'aqi', 456 ], [ 'day', 'Tuesday' ] ]
Method 3: Using Array.map()
const obj = {
city: "New Delhi",
maxTemp: 32,
minTemp: 21,
humidity: 78,
aqi: 456,
day: 'Tuesday',
};
const objectToArray = (obj) => {
return Object.keys(obj).map(key => [key, obj[key]]);
};
console.log(objectToArray(obj));
[ [ 'city', 'New Delhi' ], [ 'maxTemp', 32 ], [ 'minTemp', 21 ], [ 'humidity', 78 ], [ 'aqi', 456 ], [ 'day', 'Tuesday' ] ]
Comparison
| Method | Performance | Readability | Browser Support |
|---|---|---|---|
| Object.keys() + Loop | Good | Medium | All browsers |
| Object.entries() | Best | Excellent | ES2017+ |
| Object.keys() + map() | Good | Good | ES5+ |
Conclusion
Object.entries() is the most concise and readable approach for converting objects to 2D arrays. For older browser support, use Object.keys() with mapping or loops.
