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

如何根据ID匹配合并arr1与arr2数据,同步arr1内容至匹配项

JavaScript数组按ID匹配合并元素

需求很明确:有两个数组arr1和arr2,当两个数组里的元素ID匹配时,把arr1中对应元素的内容合并到arr2的每个匹配元素里,最终得到指定结构的结果数组。

原始数据示例:

const arr1 = [
  { id: 1, name: "omar" },
  { id: 2, name: "laith" },
  { id: 3, name: "aref" },
]

const arr2 = [
  { id: 1, rating: "good" },
  { id: 2, rating: "very good" },
  { id: 2, rating: "very good" },
  { id: 3, rating: "Excellence" },
  { id: 3, rating: "Excellence" },
]

// 预期输出
const result = [
  { id: 1, rating: "good", name: "omar" },
  { id: 1, rating: "good", name: "omar" },
  { id: 2, rating: "very good", name: "laith" },
  { id: 3, rating: "Excellence", name: "aref" },
  { id: 3, rating: "Excellence", name: "aref" },
]

实现思路

先把arr1转换成以id为键的映射对象,这样后续查找对应id的元素时,时间复杂度是O(1),比每次遍历arr1找匹配id效率高很多。然后遍历arr2,把每个元素和映射里对应id的对象合并即可。

代码实现

// 把arr1转成id映射,方便快速查找
const idMap = arr1.reduce((map, item) => {
  map[item.id] = item;
  return map;
}, {});

// 遍历arr2,合并对应id的元素
const result = arr2.map(item => ({
  ...item,
  ...idMap[item.id]
}));

console.log(result);

运行这段代码后,就能得到预期的结果数组。这里用了ES6的扩展运算符...来合并对象,若存在同名属性,arr1的属性会覆盖arr2的属性(示例中无属性冲突)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:41:25