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

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

问题描述

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

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.

推荐答案

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

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天全站免登陆