js——算法

这篇博客介绍了如何使用JavaScript将数组数据转换为树形结构,适用于组织层级关系的展示。示例中展示了将包含id和parentId的数组转换为具有children属性的树形结构对象,通过递归函数arrToTree和toTree实现。这种方法对于处理具有层级关系的数据非常有用,如组织架构、目录树等。

0 算法与结构

JavaScript 算法与数据结构 - 掘金

1.数组转树

    // 数组转树
    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: 3
    }, {
        id: 6,
        val: "学生3",
        parentId: 3
    }]
    let output = {
        id: 1,
        val: "学校",
        children: [{
            id: 2,
            val: "班级1",
            children: [{
                id: 4,
                val: "学生1",
                children: []
            }]
        }, {
            id: 3,
            val: "班级2",
            children: [{
                id: 5,
                val: "学生2",
                children: []
            }, {
                id: 6,
                val: "学生3",
                children: []
            }]
        }]
    }

    function obj(item) {
        this.id = item.id;
        this.val = item.val;
        this.children = []
    }

    function arrToTree(arr) {
        let tree = new obj(arr[0]);
        arr.shift();
        while (arr.length > 0) {
            toTree(arr[0], [tree], arr);
        }
        return tree;
    }

    function toTree(item, arr, mainarr) {
        for (let i = 0; i < arr.length; i++) {
            if (item.parentId === arr[i].id) {
                arr[i].children.push(new obj(item));
                mainarr.shift();
                break
            } else {
                 arr[i].children.length > 0 ? toTree(item, arr[i].children, mainarr) : null
            }
        }
    }
    console.log(arrToTree(input));

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值