实现一个树形结构数据加层级

<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>实现一个树形结构数据加层级</title>
</head>

<body>
  <script>
    const Tree = [{
        title: "课程1",
        id: 1,
        children: [{
            title: "数学",
            id: 100,
            children: [{
                title: "代数",
                id: 1001
              },
              {
                title: "几何",
                id: 1002
              }
            ]
          },
          {
            title: "语文",
            id: 101,
            children: [{
                title: "小学语文",
                id: 1011
              },
              {
                title: "中学语文",
                id: 1012
              }
            ]
          },
          {
            title: "英文",
            id: 102,
            children: [{
                title: "法文",
                id: 1021
              },
              {
                title: "英文文",
                id: 1022
              }
            ]
          },
        ]
      },
      {
        title: "课程2",
        id: 2,
        children: [{
            title: "生物",
            id: 200
          },
          {
            title: "化学",
            id: 201
          },
        ]
      },
      {
        title: "课程3",
        id: 3,
        children: [{
            title: "政治",
            id: 300
          },
          {
            title: "地理",
            id: 301
          },
        ]
      }
    ]


    function renderTree(Tree, level = 0) {

      const childs = []

      for (let i = 0; i < Tree.length; i++) {

        Tree[i].index = level

        if (i === Tree.length - 1) {
          if (Tree[i].children) childs.push(Tree[i].children)

          renderTree(childs.flat(Infinity), ++level)

        } else {
          if (Tree[i].children) childs.push(Tree[i].children)
        }

      }

    }

    renderTree(Tree)

  </script>
</body>

</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容