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

React JS深层嵌套数组扁平化处理技术求助

三层嵌套数组扁平化解决方案

核心思路

通过嵌套使用flatMap遍历各层级数组,结合对象展开运算符合并各层级属性,最终生成符合要求的扁平化对象数组,同时处理空数组场景避免无效数据。

示例输入数据

假设你的原始数据结构如下:

const originalData = [
  {
    id: 1,
    mainTitle: '主数据1',
    arr1: [
      {
        arr1Id: 101,
        arr1Desc: '二级数据1',
        arr2: [
          { arr2Id: 1001, arr2Content: '三级数据1' },
          { arr2Id: 1002, arr2Content: '三级数据2' }
        ]
      },
      {
        arr1Id: 102,
        arr1Desc: '二级数据2',
        arr2: [
          { arr2Id: 1003, arr2Content: '三级数据3' }
        ]
      }
    ]
  },
  {
    id: 2,
    mainTitle: '主数据2',
    arr1: [
      {
        arr1Id: 201,
        arr1Desc: '二级数据3',
        arr2: [] // 空三级数组,需要过滤
      }
    ]
  }
];

实现代码

const flattenedResult = originalData.flatMap(mainItem => {
  // 遍历二级数组arr1
  return mainItem.arr1.flatMap(arr1Item => {
    // 过滤空的三级数组,避免生成无效对象
    if (!arr1Item.arr2 || arr1Item.arr2.length === 0) {
      return [];
    }
    // 遍历三级数组arr2,合并所有层级属性
    return arr1Item.arr2.map(arr2Item => {
      return {
        // 合并主对象、二级对象、三级对象的属性
        ...mainItem,
        ...arr1Item,
        ...arr2Item,
        // 移除原嵌套数组属性,保持结构纯净
        arr1: undefined,
        arr2: undefined
      };
    });
  });
});

期望输出结果

[
  { id: 1, mainTitle: '主数据1', arr1Id: 101, arr1Desc: '二级数据1', arr2Id: 1001, arr2Content: '三级数据1' },
  { id: 1, mainTitle: '主数据1', arr1Id: 101, arr1Desc: '二级数据1', arr2Id: 1002, arr2Content: '三级数据2' },
  { id: 1, mainTitle: '主数据1', arr1Id: 102, arr1Desc: '二级数据2', arr2Id: 1003, arr2Content: '三级数据3' }
]

关键细节说明

  • flatMap的作用:替代map后再调用flat(),直接将嵌套数组展开,简化代码逻辑
  • 属性冲突处理:如果不同层级存在同名属性,后面的对象属性会覆盖前面的(比如主对象和二级对象都有id,二级的id会替换主对象的),若需保留所有同名属性,可手动重命名,例如mainId: mainItem.id
  • 空数组过滤:通过判断arr2是否为空,跳过无效的二级数据,避免生成无意义的扁平化对象
  • 清理嵌套属性:移除原有的arr1和arr2属性,确保输出数组中的对象完全扁平化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:10:39