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

如何从LOL赛事JSON中提取指定召唤师的胜负状态赋值给变量

修改方案:为matchData添加指定召唤师的胜利状态

核心思路

  1. 在原有players数组映射逻辑完成后,从原始参与者数组中找到与summoner参数匹配的对象
  2. 提取该对象的win值,赋值给matchData的victory字段
  3. 完整保留现有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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:22:45