如何从LOL赛事JSON中提取指定召唤师的胜负状态赋值给变量
修改方案:为matchData添加指定召唤师的胜利状态
核心思路
- 在原有
players数组映射逻辑完成后,从原始参与者数组中找到与summoner参数匹配的对象 - 提取该对象的
win值,赋值给matchData的victory字段 - 完整保留现有
players数组的映射逻辑,仅新增字段赋值步骤
修改后的代码示例
async function getMatchData(matchId, summoner) { // 调用Riot赛事API获取原始数据 const rawResponse = await fetch(`https://api.riotgames.com/lol/match/v5/matches/${matchId}`); const rawMatchData = await rawResponse.json(); // 保留现有players数组的映射逻辑 const players = rawMatchData.info.participants.map(participant => ({ summonerName: participant.summonerName, summonerId: participant.summonerId, championName: participant.championName, kills: participant.kills, deaths: participant.deaths, assists: participant.assists, // 其他原有映射字段保持不变 })); // 新增:匹配指定召唤师并获取胜利状态 // 优先用summonerId匹配(唯一标识,避免重名问题) const targetParticipant = rawMatchData.info.participants.find( p => p.summonerId === summoner.summonerId // 若summoner参数是名字字符串,改用:p.summonerName.toLowerCase() === summoner.toLowerCase() ); // 处理未找到召唤师的情况,可按需调整(设为null/抛出错误/返回默认值) const victory = targetParticipant ? targetParticipant.win : null; // 返回包含victory字段的最终matchData return { matchId: rawMatchData.metadata.matchId, players: players, victory: victory, // 新增的胜利状态字段 // 其他原有字段保持不变 }; }
关键说明
- 匹配准确性:优先使用
summonerId匹配召唤师,召唤师名字可能存在重复,summonerId是平台唯一标识,匹配更可靠 - 异常兼容:如果未找到指定召唤师,
victory默认设为null,你可根据业务需求改为抛出错误或返回默认值 - 无侵入性:所有原有
players数组的映射逻辑完全保留,仅新增了victory字段的赋值步骤,不会影响原有功能
内容的提问来源于stack exchange,提问作者ThePridestalker
相关产品推荐
相关产品推荐

