JS实现无限级分类

公子初心
2024-05-14 / 0 评论 / 30 阅读 / 正在检测是否收录...

Snipaste_2024-05-14_19-32-12.jpg

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let arr = [
      { id: 1, 'auth_name': '商品管理', pid: 0 },
      { id: 2, 'auth_name': '商品添加', pid: 1 },
      { id: 3, 'auth_name': '商品列表', pid: 1 },
      { id: 4, 'auth_name': '用户管理', pid: 0 },
      { id: 5, 'auth_name': '用户添加', pid: 4 },
      { id: 6, 'auth_name': '商品添加1', pid: 2 },

    ]

    function buildTree(items) {
      // 创建一个空的映射,用于存放每个id对应的节点  
      const map = new Map();

      // 遍历数组,建立id到节点的映射,并为每个节点初始化children数组  
      items.forEach(item => {
        map.set(item.id, {
          ...item,
          children: []
        });
      });

      // 遍历数组,将每个节点添加到其父节点的children数组中  
      items.forEach(item => {
        // 如果当前节点不是根节点(pid不为0)  
        if (item.pid !== 0) {
          // 从映射中获取父节点  
          const parent = map.get(item.pid);
          // 如果父节点存在,将当前节点添加到父节点的children数组中  
          if (parent) {
            parent.children.push(map.get(item.id));
          }
        }
      });

      // 过滤出根节点(pid为0)并返回  
      return Array.from(map.values()).filter(node => node.pid === 0);
    }
    const tree = buildTree(arr);
    console.log(tree);
    console.log(JSON.stringify(tree, null, 2))

  </script>
</body>

</html>
0

评论 (0)

取消