Javascript中新对象数组中数组对象属性值的总和

Javascript中新对象数组中数组对象属性值的总和

本文介绍了Javascript中新对象数组中数组对象属性值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我需要新对象数组中的对象属性值的总和,

I have an array of objects where i need sum of object property values in new array of objects,

输入:

var inputArray = [
  { subject: 'Maths', marks: '40', noOfStudents: '5' },
  { subject: 'Science', marks: '50', noOfStudents: '16' },
  { subject: 'History', marks: '35', noOfStudents: '23' },
  { subject: 'Science', marks: '65', noOfStudents: '2' },
  { subject: 'Maths', marks: '30', noOfStudents: '12' },
  { subject: 'History', marks: '55', noOfStudents: '20' },
  .
  .
  .
];

我需要的输出,

var outputArray = [
  { subject: 'Maths', marks: '70', noOfStudents: '17' },
  { subject: 'Science', marks: '115', noOfStudents: '18' },
  { subject: 'History', marks: '95', noOfStudents: '43' },
  .
  .
  .
];

我想要新对象数组中科目的总分和学生人数.输入数组中将有 N 个其他主题对象(即地理、物理等).

I want sum of marks and no of students of subjects in new object array. There would be N number of other subject objects (i.e-Geography, Physics etc) in the input array.

推荐答案

您可以使用 forEachthisArg 可选参数

You can do this with forEach and thisArg optional parameter

var inputArray = [
  { subject: 'Maths', marks: '40', noOfStudents: '5' },
  { subject: 'Science', marks: '50', noOfStudents: '16' },
  { subject: 'History', marks: '35', noOfStudents: '23' },
  { subject: 'Science', marks: '65', noOfStudents: '2' },
  { subject: 'Maths', marks: '30', noOfStudents: '12' },
  { subject: 'History', marks: '55', noOfStudents: '20' },
], outputArray = [];

inputArray.forEach(function(e) {
  if(!this[e.subject]) {
    this[e.subject] = { subject: e.subject, marks:  0, noOfStudents: 0 }
     outputArray.push(this[e.subject]);
   }
  this[e.subject].marks += Number(e.marks);
  this[e.subject].noOfStudents += Number(e.noOfStudents);
}, {});

console.log(outputArray)

这篇关于Javascript中新对象数组中数组对象属性值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:26