js实现数组转树

题目: 数组转树
比如将下面的input 转换成output结构
input:

    let input = [
      {
        id: 1,
        val: "学校",
        parentId: null,
      },
      {
        id: 2,
        val: "班级1",
        parentId: 1,
      },
      {
        id: 3,
        val: "班级2",
        parentId: 1,
      },
      {
        id: 4,
        val: "学生1",
        parentId: 2,
      },
      {
        id: 5,
        val: "学生2",
        parentId: 2,
      },
      {
        id: 6,
        val: "学生3",
        parentId: 3,
      },
    ];

output

let output = {
      id: 1,
      val: "学校",
      children: [
        {
          id: 2,
          val: "班级1",
          children: [
            {
              id: 4,
              val: "学生1",
              children: [],
            },
            {
              id: 5,
              val: "学生2",
              children: [],
            },
          ],
        },
        {
          id: 3,
          val: "班级2",
          children: [
            {
              id: 6,
              val: "学生3",
              children: [],
            },
          ],
        },
      ],
    };

方法,确定根节点之后,利用递归来构造children。
代码如下:

function toTree(arr) {
    
    
      const root = arr[0];
      arr.shift(); // 剔除根节点
      return {
    
    
        id: root.id,
        val: root.val,
        children: arr.length > 0 ? getChildren(arr, root.id) : [], //只有根节点就不遍历了
      };
    }

    //递归获取子节点
    function getChildren(arr, parentId) {
    
    
      let children = [];
      arr.forEach((item) => {
    
    
        if (item.parentId === parentId) {
    
    
          children.push({
    
    
            id: item.id,
            val: item.val,
            children: getChildren(arr, item.id),
          });
        }
      });
      return children;
    }
    console.log(toTree(input));

看一下输出的结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43682422/article/details/127519456