[英]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.