You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript遍历对象数组并累加特定属性的数值

实现方案

实现思路

  • 初始化统计对象,默认Cristiano和Maria的胜场初始值为0
  • 遍历原数组的所有比赛记录
  • 对每条比赛记录,分别取出第一、第二参与者的胜场数值,累加到统计对象对应的姓名属性中

代码实现

固定统计两人的写法

const array = [
  {
    id: '147acaa3-363c-4a28-af43-fcc035a1d500',
    arena: 'Philippine Arena',
    firstParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
      name: 'Cristiano',
      battlesWon: 0
    },
    secondParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
      name: 'Maria',
      battlesWon: 1
    },
    logs: [ [Object] ]
  },
  {
    id: 'b2ef2d28-d84d-4cc9-946f-3d57b8ce05ab',
    arena: 'Greensboro Coliseum',
    firstParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075644',
      name: 'Maria',
      battlesWon: 1
    },
    secondParticipant: {
      address: '0x3ba59bcc1a02cb46e7de35fb0bacc860bf075661',
      name: 'Cristiano',
      battlesWon: 0
    },
    logs: [ [Object] ]
  }
]

const result = array.reduce((acc, curr) => {
  acc[curr.firstParticipant.name] += curr.firstParticipant.battlesWon
  acc[curr.secondParticipant.name] += curr.secondParticipant.battlesWon
  return acc
}, {
  Cristiano: 0,
  Maria: 0
})

console.log(result)

通用兼容写法(支持后续新增任意选手自动统计)

const result = array.reduce((acc, curr) => {
  [curr.firstParticipant, curr.secondParticipant].forEach(player => {
    if (!acc[player.name]) acc[player.name] = 0
    acc[player.name] += player.battlesWon
  })
  return acc
}, {})

输出结果

{
  Cristiano: 0,
  Maria: 2
}

内容的提问来源于stack exchange,提问作者Daywison Ferreira Leal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 14:36:07