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

嵌套对象数组按重复名称过滤,限制展示3条并追加剩余数量标识

实现方案

核心思路

  • 递归处理嵌套结构:数据存在多级children嵌套,需对每一层的子数组单独做截断处理
  • 按唯一标识分组:以title + name作为分组键,统计同角色同名称的总出现次数
  • 截断追加标记:每个分组最多保留3条原始数据,超出部分统一在该分组最后一条追加剩余数量标记
  • 保留原有顺序:不同名称角色的展示顺序和原始数据完全一致

代码实现

// 可配置:同名称同角色最多展示条数
const MAX_DISPLAY = 3;

function formatData(data) {
  // 处理单层级数组
  const processList = (list) => {
    const countMap = {};
    const addedMap = {};
    const res = [];

    // 首次遍历统计每个分组总条数
    list.forEach(item => {
      const key = `${item.title}-${item.name}`;
      countMap[key] = (countMap[key] || 0) + 1;
    });

    // 二次遍历生成新数组
    list.forEach(item => {
      const key = `${item.title}-${item.name}`;
      const total = countMap[key];
      addedMap[key] = (addedMap[key] || 0) + 1;

      if (addedMap[key] <= MAX_DISPLAY) {
        // 拷贝当前项避免修改原数据
        const newItem = {...item};
        // 递归处理子级
        if (Array.isArray(newItem.children)) {
          newItem.children = processList(newItem.children);
        }
        // 超过最大展示数时给分组最后一条加标记
        if (addedMap[key] === MAX_DISPLAY && total > MAX_DISPLAY) {
          newItem.more = true;
          newItem.remaining = total - MAX_DISPLAY;
        }
        res.push(newItem);
      }
    });
    return res;
  };

  return processList(data);
}

// 调用方法,传入你的原始数据即可得到目标格式数据
const finalData = formatData(originalData);

验证说明

代码处理后的数据完全匹配你给出的预期输出:

  • 名称为Clark Kent的Teacher原出现5次,处理后保留3条,第3条新增more: true, remaining: 2字段
  • Bruce Wayne下名称为Jason Todd的Student原出现5次,处理后保留3条,第3条新增more: true, remaining: 2字段
  • 其余未超过3条的条目保持原有属性和顺序不变,嵌套层级不会被破坏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:48:03