首页 > 解决方案 > 如何使用动态键获取数组对象值的总值

问题描述

我有以下模拟数组,

这个数组是演示目的,我知道 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"
                }
            }
        ]
    }
]

我将如何使用 reduceowlCount在每个嵌套数组中添加值。无需[0]进入嵌套数组

我在想这样的事情,但我得到的值为 0,而它应该是 9

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

我做错了什么,应该有什么解决方案。

标签: javascript

解决方案


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);


推荐阅读