JS将普通数据转换成一个树状结构的数据

const rootList = [
            { id: 1, parent: null, text: '菜单1' },
            { id: 11, parent: 1, text: '菜单1-1' },
            { id: 12, parent: 1, text: '菜单1-2' },
            { id: 2, parent: null, text: '菜单2' },
            { id: 21, parent: 2, text: '菜单2-1' },
            { id: 22, parent: 2, text: '菜单2-2' },
        ]

思路:使用递归将数据拼成一个树状数据;

1.首先传入参数id为null,使用for循环,判断如果item里面的item.parent===id,此时的id为null,如果是true,则将符合条件的item添加的新的数组里

2.使用循环,给新数组里面添加children字段,调用写好的递归,参数1:源数据,2:i.id;3:i.children;返回新数组,调用该递归传参

代码如下:第一次循环会得到一个普通数组,第二次会得到带有children的数组

function getTreeList(rootList, id, newArr) {
            for (const item of rootList) {
                if (item.parent === id) {
                    newArr.push(item)
                }
            }
            console.log(newArr);

            //给数组里面再添加一个children的空数组
            for (const i of newArr) {
                i.children = [];
                getTreeList(rootList, i.id, i.children);

                if (i.children.length == 0) {
                    delete i.children
                }
            }
            console.log(newArr);
            return newArr
        }

        //将数据传入,此时id为null,并且传入一个空数组
        const res = getTreeList(rootList, null, []); 
        console.log('最终返回的数据', res);
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值