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

基于taggedFileId匹配两个数组,为array1添加rateResult字段

解决方案:根据taggedFileId匹配合并数组字段

原始数据

const array1 = [
   {
     _id: new ObjectId("639979460a52134240478a9b"),
     taggedFileId: '6399798f0a52134240478abf'
   },
   {
     _id: new ObjectId("639b576c2743a77ea2812f07"),
     taggedFileId: '639988250a52134240478b07'
   }
]

const array2 = [
  {
    fileIds: new ObjectId("639979460a52134240478a9b"),
    rateResult: 'none',
    taggedFileId: '6399798f0a52134240478abf',
    _id: new ObjectId("639c8531dcd57c7d559e6211")
  },
  {
    fileIds: new ObjectId("639b576c2743a77ea2812f07"),
    rateResult: 'none',
    taggedFileId: '639988250a52134240478b07',
    _id: new ObjectId("639c8531dcd57c7d559e6212")
  }
]

需求说明

检查array1中每个对象的taggedFileId与array2中对象的taggedFileId是否匹配,匹配成功则将array2对应对象的rateResult字段添加到array1的对应对象中。

实现方法

方法1:map + find(小数据量适用)

遍历array1,对每个元素在array2中查找匹配项,合并字段:

// 生成新数组,不修改原array1
const mergedArray = array1.map(item1 => {
  const match = array2.find(item2 => item2.taggedFileId === item1.taggedFileId);
  return match ? {...item1, rateResult: match.rateResult} : item1;
});

// 直接修改原array1的写法
array1.forEach(item1 => {
  const match = array2.find(item2 => item2.taggedFileId === item1.taggedFileId);
  if (match) item1.rateResult = match.rateResult;
});

方法2:构建映射表(大数据量更高效)

先把array2转换成以taggedFileId为键的映射表,再遍历array1取值,时间复杂度更低:

// 构建taggedFileId到rateResult的映射
const rateMap = new Map(array2.map(item => [item.taggedFileId, item.rateResult]));

// 生成合并后的新数组
const mergedArray = array1.map(item => ({
  ...item,
  ...(rateMap.has(item.taggedFileId) ? {rateResult: rateMap.get(item.taggedFileId)} : {})
}));

// 直接修改原array1的写法
array1.forEach(item => {
  if (rateMap.has(item.taggedFileId)) {
    item.rateResult = rateMap.get(item.taggedFileId);
  }
});

最终结果

执行代码后得到目标数组:

[
   {
     _id: new ObjectId("639979460a52134240478a9b"),
     taggedFileId: '6399798f0a52134240478abf',
     rateResult: 'none'
   },
   {
     _id: new ObjectId("639b576c2743a77ea2812f07"),
     taggedFileId: '639988250a52134240478b07',
     rateResult: 'none'
   }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:15:14