javascript - Determine the character length and generate json data in a dom tree structure.
某草草
某草草 2017-05-19 10:17:12
0
2
612

There is a piece of data with such a structure. There are many pieces. We need to judge the level according to the length of the level and generate the json data of the dmo tree result. How to implement it? ?

Probably produces the following structure, which is just one of the array objects.

某草草
某草草

reply all(2)
黄舟

You can’t write code in this example, please share your thoughts.

Sort by level first

Create an object for the result

Maintain another array for each level of list

Then push

A question that needs to be considered is how to deal with it if the middle level does not exist

小葫芦
    var dataJson2= [{"name":"测试2","id":"1","level": "00001"},  //5位数代表1级,10位数代表2级,以此类推
                 {"name":"**a","id":"1","level": "0000100001"},
                 {"name":"***a","id":"1","level":"000010000100001"},
                 {"name":"***a","id":"1","level":"000010000100002"},
                 {"name":"***a","id":"1","level":"000010000100003"},
                 {"name":"**a","id":"1","level": "0000100002"},
                 {"name":"**a","id":"1","level": "0000100003"},
                 {"name":"*b","id":"1","level":  "00002"}]

addTree(dataJson2);
function addTree(treeData) {
    var sortLenght=treeData[0].level.length;
    //排序
    var myArr = [];
        for(var i = 0; i < treeData.length; i++) {
            var thisIndex = treeData[i].level.length / sortLenght - 1;
            if(myArr[thisIndex] === undefined) {
                myArr[thisIndex] = []
            }
            myArr[thisIndex].push(i)
        }

            //组成梯形
    var ladderArr = [];
        for(var i = myArr.length - 1; i >= 0; i--) {
            switch(i) {
                case 0:
                    for(var l = 0; l < myArr[i].length; l++) {
                        ladderArr.push(treeData[myArr[i][l]])
                    }
                    break;
                default:
                    for(var j = 0; j < myArr[i].length; j++) {
                        var str = treeData[myArr[i][j]].level.substr(0, i * sortLenght);
                        for(var k = 0; k < myArr[i - 1].length; k++) {
                            if(treeData[myArr[i - 1][k]].level === str) {
                                if(treeData[myArr[i - 1][k]].list === undefined) treeData[myArr[i - 1][k]].list = [];
                                treeData[myArr[i - 1][k]].list.push(treeData[myArr[i][j]])
                            }
                        }
                    }
            }
        }

    var treeJson=eval(ladderArr);
}

//The solution is as above, the code is not written by me

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template