小编OCT*_*CTF的帖子

尝试在对象上使用 .reduce

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

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。

javascript

5
推荐指数
1
解决办法
72
查看次数

标签 统计

javascript ×1