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
Combine array of objects in JavaScript
Suppose, we have an array of objects that contains data about some students like this:
const arr = [{
name: 'A',
idNo: 1,
marks: {
math: 98,
sci: 97,
eng: 89
}
},
{
name: 'B',
idNo: 2,
marks: {
math: 88,
sci: 87,
eng: 79
}
},
{
name: 'C',
idNo: 3,
marks: {
math: 87,
sci: 98,
eng: 91
}
}];
console.log(arr);
[
{ name: 'A', idNo: 1, marks: { math: 98, sci: 97, eng: 89 } },
{ name: 'B', idNo: 2, marks: { math: 88, sci: 87, eng: 79 } },
{ name: 'C', idNo: 3, marks: { math: 87, sci: 98, eng: 91 } }
]
We are required to write a JavaScript function that takes in one such array. Our function should then prepare an object of properties, one property for each key that the objects currently have.
For the above array, the output should group all values by their property names:
{
name: ['A', 'B', 'C'],
idNo: [1, 2, 3],
marks: [
{ math: 98, sci: 97, eng: 89 },
{ math: 88, sci: 87, eng: 79 },
{ math: 87, sci: 98, eng: 91 }
]
}
Using reduce() and forEach()
The most efficient approach uses reduce() to build the result object and forEach() to iterate through each property:
const arr = [{
name: 'A',
idNo: 1,
marks: {
math: 98,
sci: 97,
eng: 89
}
},
{
name: 'B',
idNo: 2,
marks: {
math: 88,
sci: 87,
eng: 79
}
},
{
name: 'C',
idNo: 3,
marks: {
math: 87,
sci: 98,
eng: 91
}
}];
const combineObjects = (arr = []) => {
return arr.reduce((acc, val) => {
Object.keys(val).forEach(key => {
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(val[key]);
});
return acc;
}, {});
};
console.log(combineObjects(arr));
{
name: [ 'A', 'B', 'C' ],
idNo: [ 1, 2, 3 ],
marks: [
{ math: 98, sci: 97, eng: 89 },
{ math: 88, sci: 87, eng: 79 },
{ math: 87, sci: 98, eng: 91 }
]
}
How It Works
The function works by:
- reduce(): Creates an accumulator object that builds the final result
- Object.keys(): Gets all property names from each object
- forEach(): Iterates through each property name
- Initialization: Creates an empty array for each new property
- push(): Adds each property value to its corresponding array
Alternative Using for...in Loop
You can also use a traditional for...in loop for better readability:
const combineObjectsAlt = (arr = []) => {
const result = {};
for (let obj of arr) {
for (let key in obj) {
if (!result[key]) {
result[key] = [];
}
result[key].push(obj[key]);
}
}
return result;
};
console.log(combineObjectsAlt(arr));
{
name: [ 'A', 'B', 'C' ],
idNo: [ 1, 2, 3 ],
marks: [
{ math: 98, sci: 97, eng: 89 },
{ math: 88, sci: 87, eng: 79 },
{ math: 87, sci: 98, eng: 91 }
]
}
Conclusion
Combining arrays of objects by grouping properties is efficiently achieved using reduce() with Object.keys(). This pattern transforms object arrays into property-grouped structures for easier data manipulation.
