js - algorithm

0 Algorithms and structures

JavaScript Algorithms and Data Structures - Nuggets

1. Array to tree

    // 数组转树
    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));

Guess you like

Origin blog.csdn.net/helloyangkl/article/details/128015438