如何求和数组对象中的所有元素

时间:2018-04-19 15:46:57

标签: javascript arrays

我想在数组的对象中求和所有值,问题是如果数组长度大于2,则输出将为NaN。所以这段代码。

数据:

const data = [ 
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 10}
]

解决代码:

console.log(data.reduce((p,c) => p.price+c.price))
> 15

如果我向数据添加更多对象

const data = [ 
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 10}
]

console.log(data.reduce((p,c) => p.price+c.price))
> NaN

所以我试图压扁数据:

console.log(data.map(o) => o.reduce((p,c) => p+c))
> 20

有可能,但有没有有效的解决方案? 谢谢。

2 个答案:

答案 0 :(得分:3)

问题是你在函数reduce中考虑累加器的问题,累加器是处理程序最后处理的值,在你的情况下是一个数字而你正在尝试将数字+ price与来自参数price的当前属性c相加。此外,您需要传递初始值,在本例中为0

因此,您需要将累加器用作数字而不是具有属性price的对象:



const data = [ 
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 10}
]

console.log(data.reduce((p,c) => p + c.price, 0));




答案 1 :(得分:2)

你应该在这个方法中使用函数hander

const data = [ 
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 3},
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 11},
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 9},
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 7}
]

const res = data.reduce((total, amount) => {

  total.price += amount.price;
  console.log(total.price);
  return total;
});
console.log('total: ' + res.price);
祝你好运;)