- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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, use the concept of Object.values() along with reduce().
Following is the object −
var details = [ { studentId: 10, marks: 75, studentName: "John" }, { studentId: 10, marks: 75, studentName: "John" }, { studentId: 11, marks: 98, studentName: "Bob" } ];
Example
Following is the code to reduce and merge −
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((value, object) => { if (value[object.studentId]) { ['marks'].forEach(key => value[object.studentId][key] = value[object.studentId][key] + object[key]); } else { value[object.studentId] = { ...object }; } return value; }, {})); console.log(output);
To run the above program, use the following command −
node fileName.js.
Here, my file name is demo237.js.
Output
The output is as follows −
PS C:\Users\Amit\javascript-code> node demo237.js [ { studentId: 10, marks: 150, studentName: 'John' }, { studentId: 11, marks: 98, studentName: 'Bob' } ]
Advertisements