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
What is the best way to reduce and merge a collection of objects – JavaScript?
The best way to reduce and merge a collection of objects is to use Object.values() combined with reduce() to group objects by a key and merge their properties.
This approach is useful when you have duplicate objects and want to consolidate them, such as combining student records with the same ID.
Example Data
Consider this collection of student objects with duplicates:
var details = [
{ studentId: 10, marks: 75, studentName: "John" },
{ studentId: 10, marks: 75, studentName: "John" },
{ studentId: 11, marks: 98, studentName: "Bob" }
];
Merging Objects by Key
Here's how to merge objects with the same studentId and sum their marks:
var details = [
{ studentId: 10, marks: 75, studentName: "John" },
{ studentId: 10, marks: 75, studentName: "John" },
{ studentId: 11, marks: 98, studentName: "Bob" }
];
output = Object.values(details.reduce((accumulator, currentObject) => {
if (accumulator[currentObject.studentId]) {
// If object with this studentId exists, add marks
accumulator[currentObject.studentId].marks += currentObject.marks;
} else {
// If new studentId, create new entry
accumulator[currentObject.studentId] = { ...currentObject };
}
return accumulator;
}, {}));
console.log(output);
[
{ studentId: 10, marks: 150, studentName: 'John' },
{ studentId: 11, marks: 98, studentName: 'Bob' }
]
How It Works
The process involves three steps:
- reduce() - Iterates through the array and builds an intermediate object
-
Grouping - Uses
studentIdas the key to group similar objects - Object.values() - Extracts only the values from the grouped object to return an array
Alternative: Merging Multiple Properties
To merge multiple numeric properties, you can extend the forEach approach:
var details = [
{ studentId: 10, marks: 75, attendance: 20, studentName: "John" },
{ studentId: 10, marks: 80, attendance: 18, studentName: "John" },
{ studentId: 11, marks: 98, attendance: 25, studentName: "Bob" }
];
output = Object.values(details.reduce((accumulator, currentObject) => {
if (accumulator[currentObject.studentId]) {
// Merge multiple numeric properties
['marks', 'attendance'].forEach(key => {
accumulator[currentObject.studentId][key] += currentObject[key];
});
} else {
accumulator[currentObject.studentId] = { ...currentObject };
}
return accumulator;
}, {}));
console.log(output);
[
{ studentId: 10, marks: 155, attendance: 38, studentName: 'John' },
{ studentId: 11, marks: 98, attendance: 25, studentName: 'Bob' }
]
Conclusion
Using reduce() with Object.values() provides an efficient way to merge and consolidate object collections. This pattern is particularly useful for deduplication and data aggregation tasks.
