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
相关产品推荐
相关产品推荐

