gpt4 book ai didi

javascript - 计算 JSON 数组中值的总和

转载 作者:行者123 更新时间:2023-12-01 15:34:29 25 4
gpt4 key购买 nike

有一个这样的数组:

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 的总和, weaponsotherItems使用 ES6 功能? (我不喜欢这个:任何简单的方法都会很好。)
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);

关于javascript - 计算 JSON 数组中值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61144372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com