JavaScript 利用递归求树形结构

题意

[
  { id: 1, pid: '', name: "菜单 1" },
  { id: 2, pid: 1, name: "菜单 1-1" },
  { id: 3, pid: 1, name: "菜单 1-2" },
  { id: 4, pid: 1, name: "菜单 1-3" },
  { id: 5, pid: '', name: "菜单 2" },
  { id: 6, pid: 5, name: "菜单 2-1" },
  { id: 7, pid: 5, name: "菜单 2-2" },
]

树形结构就是通过递归将以上结构转换为以下结构

[
  {
    id: 1, pid: '', name: "菜单 1",
    children: [
      { id: 2, pid: 1, name: "菜单 1-1" },
      { id: 3, pid: 1, name: "菜单 1-2" },
      { id: 4, pid: 1, name: "菜单 1-3" }
    ]
  },
  {
    id: 5, pid: '', name: "菜单 2",
    children: [
      { id: 6, pid: 5, name: "菜单 2-1" },
      { id: 7, pid: 5, name: "菜单 2-2" }
    ]
  }
]

实现思路

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let data = [
            { id: 1, pid: '', name: "菜单 1" },
            { id: 2, pid: 1, name: "菜单 1-1" },
            { id: 3, pid: 1, name: "菜单 1-2" },
            { id: 4, pid: 1, name: "菜单 1-3" },
            { id: 5, pid: '', name: "菜单 2" },
            { id: 6, pid: 5, name: "菜单 2-1" },
            { id: 7, pid: 5, name: "菜单 2-2" },
        ]

        function fn(data, id) {
            let arr = []
            data.forEach(item => {
                if (item.pid === id) {
                    const children = fn(data, item.id);

                    if (children.length) {
                        item.children = children
                    }
                    
                    arr.push(item)
                }
            });
            return arr
        }

        console.log(fn(data, ''));
    </script>
</body>

</html>

树形结构应用场景

Snipaste_2022-10-16_18-11-11.png

评论区
头像
    头像

      

文章目录