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

如何基于obj2的id匹配关系替换obj1数组元素的id值

实现方案

思路

先把obj2转为「原始id -> externalId」的映射表,再遍历obj1替换id值即可,这种方式查找效率为O(1),数据量大的时候性能优势更明显。

完整代码

const obj1 = [ { id: 1, name: 'foo' }, { id: 2, name: 'bar' } ]
const obj2 = { A: { id: 1, externalId:'AAA' }, B: { id: 2, externalId:'BBB' } }

// 1. 构建id映射表
const idMap = Object.values(obj2).reduce((acc, cur) => {
  acc[cur.id] = cur.externalId
  return acc
}, {})

// 2. 生成新数组(不会修改原obj1)
const result = obj1.map(item => ({
  ...item,
  // 加兜底逻辑,匹配不到对应关系时保留原id
  id: idMap[item.id] ?? item.id
}))

console.log(result)
// 输出:[ { id: 'AAA', name: 'foo' }, { id: 'BBB', name: 'bar' } ]

极简替代方案(仅适合小数据量场景)

如果数据量非常小,也可以省略构建映射表的步骤,直接在遍历中匹配,写法更简洁但性能稍差:

const result = obj1.map(item => ({
  ...item,
  id: Object.values(obj2).find(v => v.id === item.id)?.externalId ?? item.id
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:57:02