js代码:
function buildTree(list){
let temp = {};
let tree = [];
for(let i in list){
temp[list[i].treeId] = list[i];
}
for(let i in temp){
if(temp[i].parentTreeId) {
if(!temp[temp[i].parentTreeId].children) {
temp[temp[i].parentTreeId].children = [];
}
temp[temp[i].parentTreeId].children.push(temp[i]);
} else {
tree.push(temp[i]);
}
}
return tree;
}
buildTree(data)
//这里需要确认的就是id(文中的treeId)和父id(parentTreeId)
//以及父子之间的联系属性(children ),对应替换就可以了
原始数据示例:
var data = [
{
"name": "aaa",
"treeId": "1",
"type": 1
},
{
"name": "bbb",
"parentTreeId": "1",
"treeId": "2",
"type": 2
},
{
"name": "ccc",
"parentTreeId": "1",
"treeId": "3",
"type": 3
},
{
"name": "ddd",
"parentTreeId": "1",
"treeId": "4",
"type": 2
},
{
"abb": "eee",
"name": "qwe123",
"parentTreeId": "2",
"treeId": "5",
"type": 1
},
{
"name": "fff",
"parentTreeId": "2",
"treeId": "6",
"type": 2
},
{
"name": "ggg",
"parentTreeId": "3",
"treeId": "7",
"type": 2
},
{
"name": "hhh",
"parentTreeId": "3",
"treeId": "8",
"type": 2
},
{
"name": "iii",
"parentTreeId": "3",
"treeId": "9",
"type": 3
},
{
"name": "jjj",
"parentTreeId": "3",
"treeId": "10",
"type": 2
},
{
"name": "kkk",
"parentTreeId": "5",
"treeId": "11",
"type": 2
},
{
"name": "lll",
"parentTreeId": "5",
"treeId": "12",
"type": 2
},
{
"name": "mmm",
"parentTreeId": "5",
"treeId": "13",
"type": 2
},
{
"name": "nnn",
"parentTreeId": "5",
"treeId": "14",
"type": 2
}
];