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
Array of objects to array of arrays in JavaScript
Converting an array of objects to an array of arrays is a common transformation in JavaScript. This is useful when you need to extract object values into a simpler array format for data processing or visualization.
Problem Statement
Suppose we have an array of objects like this:
const arr = [
{"Date":"2014","Amount1":90,"Amount2":800},
{"Date":"2015","Amount1":110,"Amount2":300},
{"Date":"2016","Amount1":3000,"Amount2":500}
];
We need to transform this into an array of arrays containing the object values:
[
['2014', 90, 800],
['2015', 110, 300],
['2016', 3000, 500]
]
Using Object.values() with map()
The most concise approach uses Object.values() to extract values from each object:
const arr = [
{"Date":"2014","Amount1":90,"Amount2":800},
{"Date":"2015","Amount1":110,"Amount2":300},
{"Date":"2016","Amount1":3000,"Amount2":500}
];
const result = arr.map(obj => Object.values(obj));
console.log(result);
[ [ '2014', 90, 800 ], [ '2015', 110, 300 ], [ '2016', 3000, 500 ] ]
Using a Custom Function
For more control or compatibility with older environments, you can use a traditional function:
const arr = [
{"Date":"2014","Amount1":90,"Amount2":800},
{"Date":"2015","Amount1":110,"Amount2":300},
{"Date":"2016","Amount1":3000,"Amount2":500}
];
const arrify = (arr = []) => {
const res = [];
const { length: l } = arr;
for(let i = 0; i < l; i++){
const obj = arr[i];
const subArr = Object.values(obj);
res.push(subArr);
}
return res;
};
console.log(arrify(arr));
[ [ '2014', 90, 800 ], [ '2015', 110, 300 ], [ '2016', 3000, 500 ] ]
Extracting Specific Properties
If you need only specific properties in a particular order, you can specify them manually:
const arr = [
{"Date":"2014","Amount1":90,"Amount2":800},
{"Date":"2015","Amount1":110,"Amount2":300},
{"Date":"2016","Amount1":3000,"Amount2":500}
];
const result = arr.map(obj => [obj.Date, obj.Amount1, obj.Amount2]);
console.log(result);
[ [ '2014', 90, 800 ], [ '2015', 110, 300 ], [ '2016', 3000, 500 ] ]
Comparison
| Method | Advantages | Use Case |
|---|---|---|
Object.values() |
Concise, handles all properties | All object values needed |
| Custom function | More control, older browser support | Complex transformations |
| Manual property access | Specific order, selective properties | Specific properties only |
Conclusion
Use arr.map(obj => Object.values(obj)) for the most concise solution. For specific properties or order control, use manual property access with destructuring or direct property references.
