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

从嵌套对象数组中移除重复父对象的技术实现

解决方案

因为需要依赖前一个元素的状态判断是否去重,单纯用filter无法实现,得用遍历+记录历史状态的方式,推荐用Array.prototype.reduce来处理:

核心思路

遍历数组时维护两个状态:

  • 最终的结果数组
  • 上一个被保留对象的最后一个image对象

对每个对象,先把images统一转成数组格式(不管原本是单个对象还是数组),然后判断当前对象的第一个image是否和上一个保留的最后一个image重复——重复就跳过这个父对象,不重复则保留并更新历史状态。

代码示例

假设每个image对象用id作为唯一标识判断重复,示例数据和处理代码如下:

// 示例数据
const data = [
  { id: 1, images: { id: 'img1' } },
  { id: 2, images: [{ id: 'img1' }, { id: 'img2' }] },
  { id: 3, images: { id: 'img3' } },
  { id: 4, images: [{ id: 'img3' }, { id: 'img4' }] },
  { id: 5, images: { id: 'img5' } }
];

// 过滤处理
const filteredData = data.reduce((acc, current) => {
  // 统一将images转为数组,方便取首尾元素
  const currentImages = Array.isArray(current.images) ? current.images : [current.images];
  const firstImage = currentImages[0];
  const lastImage = currentImages.at(-1);

  // 第一个元素直接保留
  if (acc.result.length === 0) {
    acc.result.push(current);
    acc.lastValidImage = lastImage;
    return acc;
  }

  // 判断是否和上一个保留的最后一个image重复(根据实际字段调整判断逻辑)
  const hasDuplicate = firstImage.id === acc.lastValidImage.id;

  if (!hasDuplicate) {
    acc.result.push(current);
    acc.lastValidImage = lastImage;
  }

  return acc;
}, { result: [], lastValidImage: null }).result;

console.log(filteredData);
// 输出:[{id:1,...}, {id:3,...}, {id:5,...}]

注意事项

  • 判断重复的逻辑要根据实际image对象的唯一标识调整,比如用url、uuid等字段替换示例中的id。
  • 完全保留原数组的顺序,仅移除存在重复关联的父对象,嵌套数组内部的重复项不会被处理(符合需求)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:55:18