如何计算JSON对象中两组指定字段的求和值?
问题解决:计算JSON对象中指定字段的和
首先,你的JSON数据里,homescorepoints、homeframepointsadj这类字段的值是字符串类型,必须先转成数字再相加,避免出现字符串拼接的错误结果。下面直接给你几种实用的写法:
单个比赛对象的计算
假设你已经把JSON解析成了JavaScript对象,比如存在matchData变量中,先取出目标比赛的子对象:
// 获取目标比赛数据 const match = matchData["512830"]; // 计算主队总分:homescorepoints + homeframepointsadj const homeTotal = Number(match.homescorepoints) + Number(match.homeframepointsadj); // 计算客队总分:awayscorepoints + awayframepointsadj const awayTotal = Number(match.awayscorepoints) + Number(match.awayframepointsadj); console.log(`主队总分:${homeTotal},客队总分:${awayTotal}`); // 输出结果:主队总分:192,客队总分:178
多个比赛对象的批量计算(数组场景)
如果你的数据是包含多场比赛的数组,比如:
const matches = [ {"512830": {...}}, {"512831": {...}} ];
可以用reduce批量处理,同时汇总所有比赛的总分:
const totalSummary = matches.reduce((acc, matchObj) => { // 取出每个对象里的比赛ID键 const matchKey = Object.keys(matchObj)[0]; const match = matchObj[matchKey]; const homeTotal = Number(match.homescorepoints) + Number(match.homeframepointsadj); const awayTotal = Number(match.awayscorepoints) + Number(match.awayframepointsadj); // 累加所有场次的总分 acc.totalHome += homeTotal; acc.totalAway += awayTotal; // 保存单场比赛的结果 acc.matchResults.push({ matchId: matchKey, homeTeam: match.hometeamlabel, homeTotal, awayTeam: match.awayteamlabel, awayTotal }); return acc; }, { totalHome: 0, totalAway: 0, matchResults: [] }); console.log(totalSummary);
核心注意点:
- 字符串转数字是关键,用
Number()、parseInt()或parseFloat()都可以 - 单个对象直接取字段相加即可,
reduce主要用于数组的批量累加场景
内容的提问来源于stack exchange,提问作者Damien
相关产品推荐
相关产品推荐

