首页 > 其他分享 >两次循环搞定一维数组到多位数组的转换(菜单树生成)

两次循环搞定一维数组到多位数组的转换(菜单树生成)

时间:2023-02-16 17:22:30浏览次数:34  
标签:map 搞定 菜单 const title children 数组 parentId id

原数组:

const arr = [
  { id: 1, title: '第一层1000', parentId: 0 },
  { id: 2, title: '第一层2000', parentId: 0 },
  { id: 3, title: '第二层1100', parentId: 1 },
  { id: 4, title: '第二层1200', parentId: 1 },
  { id: 5, title: '第二层1300', parentId: 1 },
  { id: 6, title: '第二层2100', parentId: 2 },
  { id: 7, title: '第二层2200', parentId: 2 },
  { id: 8, title: '第三层1110', parentId: 3 },
  { id: 9, title: '第三层1120', parentId: 3 }
];

现在要实现以下效果:

[
    {
        "id": 1,
        "title": "第一层1000",
        "parentId": 0,
        "children": [
            {
                "id": 3,
                "title": "第二层1100",
                "parentId": 1,
                "children": [
                    {
                        "id": 8,
                        "title": "第三层1110",
                        "parentId": 3,
                        "children": [ ]
                    },
                    {
                        "id": 9,
                        "title": "第三层1120",
                        "parentId": 3,
                        "children": [ ]
                    }
                ]
            },
            {
                "id": 4,
                "title": "第二层1200",
                "parentId": 1,
                "children": [ ]
            },
            {
                "id": 5,
                "title": "第二层1300",
                "parentId": 1,
                "children": [ ]
            }
        ]
    },
    {
        "id": 2,
        "title": "第一层2000",
        "parentId": 0,
        "children": [
            {
                "id": 6,
                "title": "第二层2100",
                "parentId": 2,
                "children": [ ]
            },
            {
                "id": 7,
                "title": "第二层2200",
                "parentId": 2,
                "children": [ ]
            }
        ]
    }
]

实现代码如下:

// 第一次循环
// 先按照 parentId 转成 Map
function formatToMap(arr) {
  if (!arr || !Array.isArray(arr) || !arr.length) {
    return null;
  }
  const map = {};
  for (const item of arr) {
    const { parentId } = item;
    if (!map[parentId]) {
      map[parentId] = [];
    }
    map[parentId].push(item)
  }
  return map;
}
// 第二次循环
// 从 Map 中递归提取
function formatToTree(map, parentId) {
  const result = [];
  if (!map) {
    return result;
  }
  const items = map[parentId] || [];
  if (!items.length) {
    return result;
  }
  for (const item of items) {
    const { id } = item;
    item.children = formatToTree(map, id)
  }
  result.push(...items);
  return result;
}
// 测试代码
const mapData = formatToMap(arr);
const result = formatToTree(mapData, 0)
console.log(result)

标签:map,搞定,菜单,const,title,children,数组,parentId,id
From: https://www.cnblogs.com/qmzbe/p/17127480.html

相关文章