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

JavaScript实现匹配对象数组属性后为arr1追加code属性

数组匹配追加属性的解决方案

需求说明

处理两个对象数组:

  • 当arr1中对象的id属性与arr2中对象的aid属性值匹配时,将arr2对应对象的code属性追加到arr1的对应对象中
  • 无匹配项时,为arr1对应对象添加code属性并设为空字符串
  • 最终返回处理后的arr1

原始数据

var arr1 = [
  { id: 1, name: "xxx", cn: "IN" },
  { id: 2, name: "yyy", cn: "MY" },
  { id: 3, name: "zzz", cn: "SG" },
]

var arr2 = [
  { aid: 1, code: "finance" },
  { aid: 2, code: "others" },
  { aid: 4, code: "finance" },
  { aid: 5, code: "product" },
]

你的错误尝试

你写的代码会把arr2所有的code值打包成数组赋值给每个arr1对象的code,显然不符合需求:

var result = arr1.map(e=> ({
  ...e,
  code: arr2.map(i=>i.code)
})

正确解法

方法一:构建映射表(高效推荐)

先把arr2转换成以aid为键、code为值的映射对象,再遍历arr1快速匹配,适合数据量较大的场景:

// 构建aid到code的映射表
const aidCodeMap = arr2.reduce((map, item) => {
  map[item.aid] = item.code;
  return map;
}, {});

// 处理arr1
const result = arr1.map(item => ({
  ...item,
  code: aidCodeMap[item.id] || ''
}));

方法二:直接查找匹配项(简单直观)

遍历arr1时,用find方法在arr2中查找对应匹配项,适合数据量较小的场景:

const result = arr1.map(item => {
  const matchedItem = arr2.find(i => i.aid === item.id);
  return {
    ...item,
    code: matchedItem ? matchedItem.code : ''
  };
});

预期结果

var arr1 = [
  { id: 1, name: "xxx", cn: "IN", code: 'finance'},
  { id: 2, name: "yyy", cn: "MY", code: 'others'},
  { id: 3, name: "zzz", cn: "SG", code: ''},
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:50:46