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

Angular中对比两个对象数组并移除重复项的实现方案

解决方案

匹配逻辑

从你的示例能明确,需要移除主数组中满足以下任一条件的对象,同时过滤所有空对象:

  • 对象的uniqueId与第二个数组中某一项的UniqueId一致
  • 对象的source.name与第二个数组中某一项的Name一致

代码实现(Angular/TypeScript)

// 假设你的两个数组分别是mainArray和secondArray
const mainArray = [/* 你的主数组内容 */];
const secondArray = [/* 你的第二个数组内容 */];

// 提取需要排除的标识集合,用Set提升查找效率
const excludedUniqueIds = new Set(secondArray.map(item => item.UniqueId));
const excludedSourceNames = new Set(secondArray.map(item => item.Name));

// 过滤主数组
const filteredResult = mainArray.filter(item => {
  // 过滤空对象
  if (Object.keys(item).length === 0) return false;

  // 检查是否命中排除规则
  const shouldExclude = 
    excludedUniqueIds.has(item.uniqueId) || 
    (item.source?.name && excludedSourceNames.has(item.source.name));

  // 保留不需要排除的对象
  return !shouldExclude;
});

结果验证

运行上述代码后,filteredResult会和你给出的预期结果完全一致:既移除了匹配项,也去掉了所有空对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 03:21:06