繁体   English   中英

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

[英]how to get total value of array object values using dynamic keys

我有以下模拟数组,

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

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

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

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

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

这里的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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM