简体   繁体   中英

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

I have the following mock array,

this array is demo purpose, owlCount doesnt make sense i know.

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"
                }
            }
        ]
    }
]

How would i go about using reduce to add the values owlCount within each nested array. Without doing [0] to get within the nested array

I was thinking of something like this, but i get the value of 0, when it should be 9

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

What am i doing wrong, and what should be the solution.

here acc is a number not an array, not sure why you would use acc[i]? You will have to run two reduce loops here. One for outer array and one for inner array to get the sum of owlCount from sources.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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