减少和合并对象集合的最佳方法是使用Object.values()和的概念reduce()
。
以下是对象-
var details = [ { studentId: 10, marks: 75, studentName: "John" }, { studentId: 10, marks: 75, studentName: "John" }, { studentId: 11, marks: 98, studentName: "Bob" } ];
以下是减少和合并的代码-
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);
要运行上述程序,请使用以下命令-
node fileName.js.
在这里,我的文件名为demo237.js。
输出结果
输出如下-
PS C:\Users\Amit\javascript-code> node demo237.js [ { studentId: 10, marks: 150, studentName: 'John' }, { studentId: 11, marks: 98, studentName: 'Bob' } ]