计算 JSON 数组中值的总和

Abr*_*Voy 4 javascript ecmascript-6

有一个像这样的数组:

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"
    }
]
Run Code Online (Sandbox Code Playgroud)

如何使用 ES6 功能计算coins,weapons和的总和?otherItems(我不喜欢这个:任何简单的方法都很好。)

data.reduce((first, last) => first + last)生成一串[object Object][object Object]...

mic*_*ckl 5

您必须单独处理每个字段(请注意,当您不指定第二个参数时,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);
Run Code Online (Sandbox Code Playgroud)