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
Map multiple properties in array of objects to the same array JavaScript
When working with arrays of objects in JavaScript, you often need to extract multiple property values and combine them into a single flat array. This tutorial shows different approaches to map multiple properties from an array of objects.
Problem Statement
Given an array of objects like this:
const arr = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6}
];
We need to extract all property values and create a flat array:
const output = [1, 2, 3, 4, 5, 6];
Using reduce() Method
The reduce() method accumulates values by iterating through each object and pushing properties to the result array:
const arr = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6}
];
const pushToArray = (arr = []) => {
const result = arr.reduce((acc, obj) => {
acc.push(obj.a);
acc.push(obj.b);
return acc;
}, []);
return result;
};
console.log(pushToArray(arr));
[ 1, 2, 3, 4, 5, 6 ]
Using flatMap() Method
A more concise approach uses flatMap() to map and flatten in one step:
const arr = [
{a: 1, b: 2},
{a: 3, b: 4},
{a: 5, b: 6}
];
const result = arr.flatMap(obj => [obj.a, obj.b]);
console.log(result);
[ 1, 2, 3, 4, 5, 6 ]
Dynamic Property Extraction
For a more flexible solution that works with any number of properties:
const arr = [
{a: 1, b: 2, c: 7},
{a: 3, b: 4, c: 8},
{a: 5, b: 6, c: 9}
];
const extractAllValues = (arr) => {
return arr.flatMap(obj => Object.values(obj));
};
console.log(extractAllValues(arr));
[ 1, 2, 7, 3, 4, 8, 5, 6, 9 ]
Comparison
| Method | Readability | Flexibility | Performance |
|---|---|---|---|
reduce() |
Good | Manual property selection | Good |
flatMap() |
Excellent | Manual property selection | Better |
Object.values() |
Excellent | All properties automatically | Good |
Conclusion
Use flatMap() for the cleanest code when selecting specific properties, or combine it with Object.values() for dynamic extraction of all properties from objects.
