如何将结果数组归约为含用户ID、积分总和及获胜次数的对象数组
问题修复方案
错误点分析
- 拼写错误:代码中多次使用
cur.profile读取属性,实际字段名是cur.profileid,导致无法正确读取已累加的统计值 - 胜场统计逻辑错误:首次遇到
winner: true的记录时,你返回的初始值是0,应该设为1才能正确计数 - 数据格式不匹配:你当前的聚合逻辑是按对象键值对分组的,所以reduce初始值应该设为空对象
{},聚合完成后再用Object.values()把对象转成你需要的数组格式
修复后代码
const data = [ { profileid: '1', points: 25, winner: true }, { profileid: '2', points: 15, winner: false }, { profileid: '3', points: 18, winner: false }, { profileid: '1', points: 15, winner: false }, { profileid: '2', points: 18, winner: false }, { profileid: '3', points: 25, winner: true }, ] // 第一步:按profileid分组聚合为对象 const groupResult = data.reduce((acc, cur) => { // 读取已有统计记录,不存在则初始化 const existRecord = acc[cur.profileid] ?? { profileid: cur.profileid, points: 0, wins: 0 } return { ...acc, [cur.profileid]: { ...existRecord, points: existRecord.points + cur.points, wins: existRecord.wins + (cur.winner ? 1 : 0) } } }, {}) // 第二步:将聚合对象的值转为数组 const result = Object.values(groupResult) console.log(result)
输出验证
运行后输出结果和你给出的预期完全一致:
[ { profileid: '1', points: 40, wins: 1 }, { profileid: '2', points: 33, wins: 0 }, { profileid: '3', points: 43, wins: 1 } ]
内容的提问来源于stack exchange,提问作者Jason McFarlane
相关产品推荐
相关产品推荐

