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

如何在JavaScript中根据ID匹配替换数组中的球员数据

解决方案:将球队数组中的球员ID替换为对应球员详情对象

输入数据

原始球队数组:

const teams = [
  {
    "teamName": "TeamA",
    "players": ["1","2"]
  },
  {
    "teamName": "TeamB",
    "players": ["2"]
  }
];

球员详情数组:

const players = [
  {
    "id": "1",
    "playername": "alex"
  },
  {
    "id": "2",
    "playername": "john"
  }
];

高效实现代码

步骤1:创建球员ID映射表

先把球员详情转换成以ID为键的Map,这样可以快速通过ID查找对应的球员对象,避免重复遍历数组:

const playerMap = new Map();
players.forEach(player => {
  playerMap.set(player.id, player);
});

步骤2:转换球队数组

通过map方法遍历球队数组,替换每个球队的players字段:

// 生成新数组,不修改原数据
const updatedTeams = teams.map(team => ({
  ...team,
  players: team.players.map(playerId => playerMap.get(playerId))
}));

// 输出结果
console.log(JSON.stringify(updatedTeams, null, 2));

如果需要直接修改原数组,可改用forEach:

// 直接修改原teams数组
teams.forEach(team => {
  team.players = team.players.map(playerId => playerMap.get(playerId));
});

输出结果

运行后会得到你期望的结构:

[
  {
    "teamName": "TeamA",
    "players": [
      {
        "id": "1",
        "playername": "alex"
      },
      {
        "id": "2",
        "playername": "john"
      }
    ]
  },
  {
    "teamName": "TeamB",
    "players": [
      {
        "id": "2",
        "playername": "john"
      }
    ]
  }
]

为什么比嵌套for循环更好?

  • 嵌套for循环的时间复杂度是O(n*m)(n是球队数,m是球员数),而用Map的方式时间复杂度是O(n+m),性能更优,尤其是数据量较大时。
  • 代码更简洁易读,避免了多层循环的嵌套逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:55:18