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

Node.js中如何通过team_id匹配合并两个对象数组生成新数组

Node.js 按指定字段合并两个对象数组实现方案

你可以通过先将arr2转换为以team_id为键的映射表,再遍历arr1合并对应属性的方式实现需求,该方案时间复杂度为O(n+m),数组元素量大时效率远高于嵌套循环。

具体实现代码如下:

// 示例输入数组
const arr1 = [
  {team_id:1, name: "kamal", age: "18"},
  {team_id:2, name: "nimal", age: "28"}
];
const arr2 = [
  {team_id:1, team_color : "red", team_name: 'team1'},
  {team_id:2, team_color : "green", team_name: 'team2'},
  {team_id:3, team_color : "blue", team_name: 'team3'}
];

// 1. 将arr2转为team_id为key的Map,方便快速查找
const teamInfoMap = new Map(arr2.map(item => [item.team_id, item]));

// 2. 遍历arr1,合并对应团队信息
const arr3 = arr1.map(item => {
  // 若需要兼容不支持扩展运算符的低版本Node.js,可替换为 Object.assign({}, item, teamInfoMap.get(item.team_id))
  return {...item, ...teamInfoMap.get(item.team_id)};
});

console.log(arr3);

运行后输出的arr3就和你需要的结果完全一致,且只会保留arr1中存在的team_id对应的合并对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 18:15:05