What is the best way to reduce and merge a collection of objects – JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' }
]
raja
Published on 03-Oct-2020 15:17:19
Advertisements