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.
黄舟2017-05-19 10:19:12
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
高洛峰2017-05-19 10:19:12
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