宇阳 一直对网站开发领域很感兴趣,从小就希望有一个属于自己的网站,在17年时候成功进入站长圈,并通过各种自学,以及各种折腾,才有了你现在看到的这个网站
歌曲封面 未知作品

网站已运行 5 年 70 天 4 小时 41 分

Powered by Typecho & Sunny

3 online · 52 ms

Title

JavaScript 利用递归求树形结构

宇阳

·

Article
⚠️ 本文最后更新于2023年04月01日,已经过了362天没有更新,若内容或图片失效,请留言反馈

题意

♾️ 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" },
]

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

♾️ javascript 代码:
[
  {
    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" }
    ]
  }
]

实现思路

♾️ html 代码:
<!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
现在已有 1 条评论,0 人点赞
Comment
发表
  1. 头像
    @
    该回复疑似异常,已被系统拦截!
    · Windows · Chrome · 中国江苏省电信

    👍

    💖

    💯

    💦

    😄

    🪙

    👍 0 💖 0 💯 0 💦 0 😄 0 🪙 0
搜 索 消 息 足 迹
你还不曾留言过..
你还不曾留下足迹..
博主