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

JavaScript根据指定键匹配合并两个对象数组的实现方法

按指定多键合并两个对象数组实现方案

已知条件

  • 匹配键规则:仅当两个对象的year_and_month、name字段值完全相等时,判定为可合并的同一项
  • 字段分布:
    • firstData数组对象:包含匹配键字段,独有data1、data2字段
    • secondData数组对象:包含匹配键字段,独有data3、data4字段
  • 合并要求:匹配成功的项合并全部属性,最终返回合并完成的对象数组

可直接运行的实现代码

// 预定义匹配键
const keys = ["year_and_month", "name"];

function mergeTwoArrByMatchKeys(arr1, arr2, matchKeys) {
  // 先遍历第一个数组,匹配第二个数组中的对应项做合并
  const mergedResult = arr1.map(item1 => {
    // 多键全值相等匹配逻辑
    const matchItem = arr2.find(item2 => {
      return matchKeys.every(key => item1[key] === item2[key]);
    });
    // 匹配到就合并所有属性,没匹配到保留arr1原项
    return matchItem ? { ...item1, ...matchItem } : item1;
  });

  // 如果需要保留arr2中未在arr1匹配到的项,放开下面这段注释即可
  // const arr2MatchedFlags = new Array(arr2.length).fill(false);
  // arr1.forEach(item1 => {
  //   const matchIndex = arr2.findIndex(item2 => matchKeys.every(key => item1[key] === item2[key]));
  //   if (matchIndex > -1) arr2MatchedFlags[matchIndex] = true;
  // })
  // arr2.forEach((item, index) => {
  //   if (!arr2MatchedFlags[index]) mergedResult.push(item);
  // })

  return mergedResult;
}

// 调用方式
const finalResult = mergeTwoArrByMatchKeys(firstData, secondData, keys);

核心逻辑说明

  • 多键匹配判断:用Array.every()遍历所有匹配键,逐一对比两个对象对应键的值,全部相等才判定为匹配,解决了多字段同时校验的问题
  • 属性合并:用对象展开运算符合并两个匹配对象的全部属性,因为匹配键的值完全一致,不会出现匹配键值覆盖冲突的问题
  • 未匹配项处理:默认保留firstData中未匹配到secondData项的原数据,如果需要保留secondData的未匹配项,放开代码中对应注释段即可

合并后单条数据结构示例

{
  year_and_month: "2024-06",
  name: "业务数据A",
  data1: 123,
  data2: 456,
  data3: 789,
  data4: 101
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 18:15:51