尝试在对象上使用 .reduce

OCT*_*CTF 5 javascript

所以我有一个对象,我需要对所有对象的嵌套值求和。我的对象看起来像

const json = [
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 10,
            "unit": 25
        },
        "updated": "2020-06-05"
    }
},
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 20,
            "unit": 5
        },
        "updated": "2020-06-05"
    }
},
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 5,
            "unit": 15
        },
        "updated": "2020-06-05"
    }
},
];
Run Code Online (Sandbox Code Playgroud)

我需要对所有“单位”值求和

我一直在尝试为此使用 .reduce,但它仅在我的对象中有 2 个项目时才有效,一旦我得到第 3 个项目,我就会收到错误消息。

我的其余代码如下:

const r = json.reduce((a, b) => a.summary.calculations.unit + b.summary.calculations.unit);
console.log(r);
Run Code Online (Sandbox Code Playgroud)

不太确定我在做什么错 atm。

ade*_*ago 4

因为那不是可行的方法reduce。摘自这篇文章,它的工作原理如下:

给定

arrSum = function(arr){
  return arr.reduce(function(a,b){
    return a + b
  }, 0);
}
Run Code Online (Sandbox Code Playgroud)

我们作为reduce 方法的第一个参数传递的函数接收两个参数,a和b。在此代码中,a是我们的累加器。当我们的函数运行时,它会累积我们的总和。b是当前正在处理的值。

所以基本上你试图访问累加器中的“摘要”,它只是一个数字。这是工作片段:

arrSum = function(arr){
  return arr.reduce(function(a,b){
    return a + b
  }, 0);
}
Run Code Online (Sandbox Code Playgroud)