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

JavaScript中如何按指定player id过滤API返回的JSON数据

实现代码

你可以直接使用Array.find()方法对返回的数组做匹配过滤,完整实现如下:

// 替换为你要提取的目标玩家ID
const TARGET_PLAYER_ID = 1011;

fetch(url)
  .then(response => response.json())
  .then((data) => {
    // 匹配ID一致的玩家数据
    const matchedPlayer = data.response.find(
      item => item.player.id === TARGET_PLAYER_ID
    )?.player;

    if (matchedPlayer) {
      // 这里的matchedPlayer就是你需要的完整player结构数据
      console.log(matchedPlayer);
      // 后续业务逻辑可以写在这里
    } else {
      console.log(`未找到ID为${TARGET_PLAYER_ID}的对应玩家`);
    }
  })
  .catch(err => console.error('数据请求/处理失败:', err));
补充说明
  • 代码中使用可选链?.是为了避免无匹配数据时报错,无匹配时matchedPlayer会返回undefined
  • 如果你需要同时提取多个指定ID的玩家数据,可以将find替换为filter+map组合实现:
// 要提取的多个玩家ID列表
const TARGET_IDS = [1011, 14268];
const matchedPlayers = data.response
  .filter(item => TARGET_IDS.includes(item.player.id))
  .map(item => item.player);

内容的提问来源于stack exchange,提问作者PeraDev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:54:03