如何对对象中特定键的所有值求和?

Phi*_* YS -1 javascript arrays node.js ecmascript-5 ecmascript-6

假设我有一个包含多个对象的数组,如:

var arr = [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}]
Run Code Online (Sandbox Code Playgroud)

我想creditarr数组中得到所有值的总和.所以期望的总和值是3.所以我用这个代码:

arr.reduce((obj, total) => obj.credit + total)

但是当我跑这个时,我觉得"1[object Object]"这真的很奇怪.

Ps:我正在尝试使用ES6而不是ES5来实现这一点

nvi*_*oli 7

两个问题:你的totalobj参数是倒退的,你需要提供一些东西来初始化total变量(那是,0部分)

arr.reduce((total, obj) => obj.credit + total,0)
// 3
Run Code Online (Sandbox Code Playgroud)


dfe*_*enc 5

您可以在这里使用.forEach()

var arr = [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}];

var total = 0;
arr.forEach(item => {
    total += item.credit;
});
  
console.log(total);
Run Code Online (Sandbox Code Playgroud)