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));

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

godlike-icy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值