树形数据针对子集平铺

const listfalse = {
    list: [
        {
          id: 'asdssfdff',
          name: '杨紫',
          code: '3333',
          parentId: null,
          parentName: null,
          isDeleted: 0,
          children: [
            {
          
              id: 'ffsssdsfff',
              name: '山河',
              code: '444444',
              parentId: 'asdssfdff',
              parentName: '杨紫',
              isDeleted: 0,
              children: [
                {
                  id: 'ffsssdsfff',
                  name: '大海',
                  code: '789',
                  parentId: 'asdssfdff',
                  parentName: '杨紫',
                  children: null,
                },
              ],
            },
          ],
        },
        {
            id: 'wwwww',
            name: '123',
            code: 'XS2024010087',
            parentId: null,
            parentName: null,
            isDeleted: 0,
            children: [
              {
                id: 'vvvvv',
                name: '赵丽颖',
                code: '55',
                parentId: 'wwwww',
                parentName: '123',
                isDeleted: 0,
                children: [
                  {
                    id: 'vvvv',
                    name: '杨幂',
                    code: '66',
                    parentId: 'wwwww',
                    parentName: '123',
                  
                    children: null,
                  },
                ],
              },
            ],
          },
    ],
}
function collectChildren(obj) {
    let result = []
    // 遍历对象的属性
    for (let key in obj) {
      if (key === 'children' && Array.isArray(obj[key])) {
        // 如果属性值是数组,直接将其加入到结果数组中
        result = result.concat([{ ...obj[key][0], children: null }])
        if (obj[key][0].children) {
          result = result.concat(collectChildren(obj[key]))
        }
      } else if (typeof obj[key] === 'object' && obj[key] !== null) {
        // 如果属性值是对象,递归调用 collectChildren 函数,并将结果合并到当前的结果数组中
        result = result.concat(collectChildren(obj[key]))
      }
    }
  
    return 
}
const collectChildrens = collectChildren(listfalse)

//   平铺出来
[
    // 第一集的两个--
    {
          
        id: 'ffsssdsfff',
        name: '山河',
        code: '444444',
        parentId: 'asdssfdff',
        parentName: '杨紫',
        isDeleted: 0,
      
      },
    
    {
        id: 'ffsssdsfff',
        name: '大海',
        code: '789',
        parentId: 'asdssfdff',
        parentName: '杨紫',
        children: null,
      },
    //   第二集的两个
      {
        id: 'vvvvv',
        name: '赵丽颖',
        code: '55',
        parentId: 'wwwww',
        parentName: '123',
      
        isDeleted: 0,
      
      },
      {
        id: 'vvvv',
        name: '杨幂',
        code: '66',
        parentId: 'wwwww',
        parentName: '123',
      
        children: null,
      },
]

你可能感兴趣的:(前端)