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

Angular8中如何根据匹配条件替换数组对象值

合并数组:匹配双字段替换对象,保留原数组无匹配项

需求说明

将oldArray与newArray合并,规则如下:

  • 当两个数组中的对象**同时匹配makeLineName和makeProcessTypeId**时,用newArray的对应对象替换oldArray中的对象;
  • 若newArray中没有匹配makeLineName(结合makeProcessTypeId)的对象,则保留oldArray的原对象。

示例数据

const oldArray = [
  {       
    makeLineName: "TestDemo1",
    makeProcessTypeId: "type1",
    avtBCT: 80,
    MaxBCT: 80
  },
  {      
    makeLineName: "Test565",
    makeProcessTypeId: "type2",
    avtBCT: '',
    MaxBCT: ''
  },
  {      
    makeLineName: "Luck", 
    makeProcessTypeId: "type3",
    avtBCT: 60,
    MaxBCT: 60
  }
];

const newArray = [
  {       
    makeLineName: "TestDemo1",
    makeProcessTypeId: "type1",
    avtBCT: 500,
    MaxBCT: 500
  },
  {      
    makeLineName: "Test565",
    makeProcessTypeId: "type2",
    avtBCT: 600,
    MaxBCT: 600
  }
];

解决方案

通过Map构建高效查找表,再遍历原数组完成替换,时间复杂度为O(n),适合处理大数据量:

// 构建newArray的映射表,用双字段组合作为唯一匹配键
const newItemMap = new Map();
newArray.forEach(item => {
  const matchKey = `${item.makeLineName}-${item.makeProcessTypeId}`;
  newItemMap.set(matchKey, item);
});

// 遍历oldArray,替换匹配项,保留无匹配元素
const filteredData = oldArray.map(oldItem => {
  const matchKey = `${oldItem.makeLineName}-${oldItem.makeProcessTypeId}`;
  return newItemMap.get(matchKey) || oldItem;
});

预期输出

const filteredData = [
  {       
    makeLineName: "TestDemo1",
    makeProcessTypeId: "type1",
    avtBCT: 500,
    MaxBCT: 500
  },
  {      
    makeLineName: "Test565",
    makeProcessTypeId: "type2",
    avtBCT: 600,
    MaxBCT: 600
  },
  {      
    makeLineName: "Luck", 
    makeProcessTypeId: "type3",
    avtBCT: 60,
    MaxBCT: 60
  }
];

补充说明

如果场景中只需匹配makeLineName单字段,只需将matchKey改为item.makeLineName即可,代码逻辑无需大改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:21:31