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

如何根据关联id合并两个数据库对象数组?

合并两个对象数组:按匹配条件整合属性

我有两个来自数据库的对象数组A(array_a)和B(array_b),需要将数组B中满足A[n].id == B[n].a_id条件的对象属性合并到数组A对应的对象中。

示例代码

const array_a = [
  {
    "id": 4,
    "status": 0,
  },
  {
    "id": 5,
    "status": 1,
  }
];

const array_b = [{
  active: 1,
  a_id: 5, // 匹配用的键
  created_at: '2022-11-05 20:29:29',
  firstname: 'user3',
  lastname: ''
}];

期望结果

const result = [
  {
    "id": 4,
    "status": 0,
  },
  {
    "id": 5,
    "status": 1,
    "active": 1,
    "user_id": 5,
    "created_at": '2022-11-05 20:29:29',
    "firstname": 'user3',
    "lastname": ''
  }
];

我尝试过一个Stack Overflow的方案但没成功,这里给你一个可行的解决办法:

解决方案

先把数组B转换成以a_id为键的Map,这样查找匹配项的效率会很高,之后遍历数组A,逐个匹配并合并属性即可,同时处理a_id转user_id的需求:

const array_a = [
  {
    "id": 4,
    "status": 0,
  },
  {
    "id": 5,
    "status": 1,
  }
];

const array_b = [{
  active: 1,
  a_id: 5,
  created_at: '2022-11-05 20:29:29',
  firstname: 'user3',
  lastname: ''
}];

// 将array_b转为Map,用a_id作为键,快速查找对应的对象
const bMap = new Map(array_b.map(item => [item.a_id, item]));

// 遍历array_a,合并匹配的属性
const result = array_a.map(item => {
  const matched = bMap.get(item.id);
  if (matched) {
    // 解构出a_id,把剩余属性和原对象合并,同时添加user_id字段
    const { a_id, ...restProps } = matched;
    return { ...item, ...restProps, user_id: a_id };
  }
  // 没有匹配项时返回原对象的副本,避免修改原数组
  return { ...item };
});

console.log(result);

方案说明

  • 用Map存储数组B的映射,查找时间复杂度是O(1),整体处理的时间复杂度为O(n+m)(n是array_a长度,m是array_b长度),比嵌套循环的O(n*m)高效得多,适合大数据量场景。
  • 用对象解构和扩展运算符合并属性,代码简洁且不会修改原数组的对象,避免副作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:01:17