数组中对象的总和 [英] Sum values of objects in array

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

问题描述

我想创建一个包含多个对象的数组的总和。

I would like to create a sum of an array with multiple objects.

这里是一个示例:
var array = [{ adults:2, children:3},{ adults:2, children:1}];

如何将每个成年人和一个小孩的总和返回一个新变量?

How do I return the sum of adults and the sum of children into a new variable for each?

谢谢,
c。

Thanks, c.

推荐答案


使用 Array.prototype.reduce() ,reduce()方法对一个累加器和数组的每个值(从左到右)应用一个函数,以将其减少为单个值。

var array = [{
  "adults": 2,
  "children": 3
}, {
  "adults": 2,
  "children": 1
}];

var val = array.reduce(function(previousValue, currentValue) {
  return {
    adults: previousValue.adults + currentValue.adults,
    children: previousValue.children + currentValue.children
  }
});
console.log(val);

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆