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
Selected Reading
Best way to flatten an object with array properties into one array JavaScript
When you have an object containing arrays as values, you often need to flatten all these arrays into a single array. This is a common operation when working with grouped data.
const obj = {
arr_a: [9, 3, 2],
arr_b: [1, 5, 0],
arr_c: [7, 18]
};
console.log("Original object:", obj);
Original object: { arr_a: [ 9, 3, 2 ], arr_b: [ 1, 5, 0 ], arr_c: [ 7, 18 ] }
The goal is to merge all array values into one flattened array: [9, 3, 2, 1, 5, 0, 7, 18].
Using Object.values() and flat() (Recommended)
The most concise approach uses Object.values() to get all arrays, then flat() to merge them:
const obj = {
arr_a: [9, 3, 2],
arr_b: [1, 5, 0],
arr_c: [7, 18]
};
const flattenObject = (obj) => {
return Object.values(obj).flat();
};
console.log(flattenObject(obj));
[ 9, 3, 2, 1, 5, 0, 7, 18 ]
Using for...in Loop with Spread Operator
A more explicit approach using a loop to iterate through object properties:
const obj = {
arr_a: [9, 3, 2],
arr_b: [1, 5, 0],
arr_c: [7, 18]
};
const objectToArray = (obj = {}) => {
const result = [];
for (let key in obj) {
const array = obj[key];
result.push(...array);
}
return result;
};
console.log(objectToArray(obj));
[ 9, 3, 2, 1, 5, 0, 7, 18 ]
Using Array.concat() with reduce()
Another functional approach using reduce() to concatenate arrays:
const obj = {
arr_a: [9, 3, 2],
arr_b: [1, 5, 0],
arr_c: [7, 18]
};
const flattenWithReduce = (obj) => {
return Object.values(obj).reduce((acc, arr) => acc.concat(arr), []);
};
console.log(flattenWithReduce(obj));
[ 9, 3, 2, 1, 5, 0, 7, 18 ]
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
Object.values().flat() |
Excellent | Good | ES2019+ |
for...in with spread |
Good | Excellent | ES2015+ |
reduce() with concat() |
Good | Good | ES5+ |
Handling Edge Cases
const emptyObj = {};
const mixedObj = {
arr1: [1, 2],
arr2: [],
arr3: [3, 4, 5]
};
console.log("Empty object:", Object.values(emptyObj).flat());
console.log("Mixed object:", Object.values(mixedObj).flat());
Empty object: [] Mixed object: [ 1, 2, 3, 4, 5 ]
Conclusion
Object.values().flat() is the most concise and readable method for flattening object arrays. For older browser support, use the for...in loop with spread operator.
Advertisements
