javascript - 计算 JSON 数组中值的总和
问题描述
有一个这样的数组:
const data = [
{
"name": "Dave",
"coins": 14,
"weapons": 2,
"otherItems": 3,
"color": "red"
},
{
"name": "Vanessa",
"coins": 18,
"weapons": 1,
"otherItems": 5,
"color": "blue"
},
{
"name": "Sharon",
"coins": 9,
"weapons": 5,
"otherItems": 1,
"color": "pink"
},
{
"name": "Walter",
"coins": 9,
"weapons": 2,
"otherItems": 4,
"color": "white"
}
]
如何计算coins
和使用 ES6 特性weapons
的总和?otherItems
(我不喜欢这个:任何简单的方法都会很好。)
data.reduce((first, last) => first + last)
生成一个链[object Object][object Object]
...
解决方案
您必须分别处理每个字段(请注意,当您不指定第二个参数时,reduce
它将第一个数组对象作为种子并从第二个开始处理):
const data = [
{
"name": "Dave",
"coins": 14,
"weapons": 2,
"otherItems": 3,
"color": "red"
},
{
"name": "Vanessa",
"coins": 18,
"weapons": 1,
"otherItems": 5,
"color": "blue"
},
{
"name": "Sharon",
"coins": 9,
"weapons": 5,
"otherItems": 1,
"color": "pink"
},
{
"name": "Walter",
"coins": 9,
"weapons": 2,
"otherItems": 4,
"color": "white"
}
]
let result = data.reduce((a,c)=> ({
coins: a.coins + c.coins,
weapons: a.weapons + c.weapons,
otherItems: a.otherItems + c.otherItems })
)
console.log(result);
推荐阅读
- tfs - TFS 2017 - 有没有办法创建一个 NET NEW 独立工作项(表单)?
- c - 什么时候需要 execle 而不是 execl?
- javascript - Jacada 扩展 - 无法分配变量
- windows - rm -f 命令导致 React.js 出错
- javascript - 块拆分中的自定义模块目录在 Webpack 中不起作用
- google-apps-script - 如何取消其他人在我的电子表格上创建的表单的链接
- ios - 从地图 SWIFT 4.1 中删除选定的 MKAnnotation 时删除错误显示的注释
- python - 使用 openpyxl 查找包含具有特定值的单元格的行
- c++ - 为什么 FlowMonitor 不为 ns3 中的 dsr.cc 收集数据?
- html -
用set引用当前目录