首页 > 解决方案 > 计算 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]...

标签: javascriptecmascript-6

解决方案


您必须分别处理每个字段(请注意,当您不指定第二个参数时,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);


推荐阅读