如何使用动态键获取数组对象值的总值

时间:2019-10-08 22:42:05

标签: javascript

我有以下模拟数组

此数组是演示目的,owlCount我没有道理。

let arr = [
    {
        "id": "000701",
        "status": "No Source Info",
        "sources": []
    },
    {
        "id": "200101",
        "status": "Good",
        "sources": [
            {
                "center": "H2",
                "uri": "237.0.1.133",
                "owlCount": 1,
                "status": "Good",
                "state": {
                    "authState": "authorized",
                    "lockState": "locked"
                }
            }
        ]
    },
    {
        "id": "005306",
        "status": "Good",
        "sources": [
            {
                "center": "H1",
                "uri": "237.0.6.5",
                "owlCount": 3,
                "status": "Good",
                "state": {
                    "authState": "authorized",
                    "lockState": "locked"
                }
            },
            {
                "center": "H1",
                "uri": "237.0.6.25",
                "owlCount": 5,
                "status": "Good",
                "state": {
                    "authState": "authorized",
                    "lockState": "locked"
                }
            }
        ]
    }
]

我将如何使用reduce在每个嵌套数组中添加值owlCount。无需执行[0]即可进入嵌套数组

我在想像这样的东西,但是当它应该为9时,我得到的值为0

const sum = arr.reduce( (acc, cv, i) => {
    acc[i] += cv.owlCount
return acc
}, 0)

我做错了什么,应该怎么解决。

1 个答案:

答案 0 :(得分:2)

这里acc是一个数字而不是数组,不确定为什么要使用acc [i]吗? 您将必须在此处运行两个reduce循环。一个用于外部数组,一个用于内部数组,以从源中获取owlCount的总和。

let arr = [
    {
        "id": "000701",
        "status": "No Source Info",
        "sources": []
    },
    {
        "id": "200101",
        "status": "Good",
        "sources": [
            {
                "center": "H2",
                "uri": "237.0.1.133",
                "owlCount": 1,
                "status": "Good",
                "state": {
                    "authState": "authorized",
                    "lockState": "locked"
                }
            }
        ]
    },
    {
        "id": "005306",
        "status": "Good",
        "sources": [
            {
                "center": "H1",
                "uri": "237.0.6.5",
                "owlCount": 3,
                "status": "Good",
                "state": {
                    "authState": "authorized",
                    "lockState": "locked"
                }
            },
            {
                "center": "H1",
                "uri": "237.0.6.25",
                "owlCount": 5,
                "status": "Good",
                "state": {
                    "authState": "authorized",
                    "lockState": "locked"
                }
            }
        ]
    }
]
const sum = arr.reduce( (acc, item) => {
    return acc += item.sources.reduce((a,source) => a += source.owlCount ,0)
}, 0)

console.log(sum);