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"
}
}
]
}
]
我将如何使用 reduceowlCount
在每个嵌套数组中添加值。无需[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);
推荐阅读
- c++ - 无法运行具有 CPP 代码 pthread_setschedparam() 的 docker 容器
- angular - Angular:mat-error 不适用于自定义验证器
- twilio - Twilio 设备设置 - 注册、连接到 TWiML 应用程序,但不接受呼叫
- node.js - 使用 LDAP NodeJs 的通用登录
- android - 用户登录时,Wordpress Webview 不显示下拉列表中的值?
- azure - 通过 terraform for azure 增加 /home 分区
- networking - Ping 请求因 ARP 错误而失败?
- android - 如何知道 viewModel 的工作何时完成
- c++ - 在 C++ Ubuntu 中安装 FTP 客户端(库)
- elasticsearch - 弹性搜索问题“iphone”没有显示正确的结果