由于業(yè)務中經常要用到一維數組轉樹形結構的函數特此記錄下
我們經常從服務器中拿到如下的一維數組
var nodes = [
{"id":1,"pId":0,"name":"父節(jié)點1 - 展開","open":true},
{"id":11,"pId":1,"name":"父節(jié)點11 - 折疊"},
{"id":12,"pId":1,"name":"父節(jié)點12 - 折疊"},
{"id":13,"pId":1,"name":"父節(jié)點13 - 沒有子節(jié)點"},
{"id":2,"pId":0,"name":"父節(jié)點2 - 折疊"},
{"id":21,"pId":2,"name":"父節(jié)點21 - 展開","open":true},
{"id":22,"pId":2,"name":"父節(jié)點22 - 折疊"},
{"id":23,"pId":2,"name":"父節(jié)點23 - 折疊"},
{"id":3,"pId":0,"name":"父節(jié)點3 - 沒有子節(jié)點"}
];
但是在業(yè)務上我們想要的是樹形文檔結構的數組樹
如下
var tree = [
{
"id": 1,
"pId": 0,
"name": "父節(jié)點1 - 展開",
"open": true,
"children": [
{
"id": 11,
"pId": 1,
"name": "父節(jié)點11 - 折疊"
},
{
"id": 12,
"pId": 1,
"name": "父節(jié)點12 - 折疊"
},
{
"id": 13,
"pId": 1,
"name": "父節(jié)點13 - 沒有子節(jié)點"
}
]
},
{
"id": 2,
"pId": 0,
"name": "父節(jié)點2 - 折疊",
"children": [
{
"id": 21,
"pId": 2,
"name": "父節(jié)點21 - 展開",
"open": true
},
{
"id": 22,
"pId": 2,
"name": "父節(jié)點22 - 折疊"
},
{
"id": 23,
"pId": 2,
"name": "父節(jié)點23 - 折疊"
}
]
},
{
"id": 3,
"pId": 0,
"name": "父節(jié)點3 - 沒有子節(jié)點"
}
]
1.使用遞歸方式將 nodes --> tree
function getTree(data, root, idTxt, pidTxt, pushTxt) {
var idTxt = idTxt || 'id';
var pidTxt = pidTxt || 'pid';
var pushTxt = pushTxt || 'children';
// 遞歸方法
function getNode(id) {
var node = []
for (var i = 0; i < data.length; i++) {
if (data[i][pidTxt] == id) {
data[i][pushTxt] = getNode(data[i][idTxt])
node.push(data[i])
}
}
if (node.length == 0) {
return
} else {
return node
}
}
// 使用根節(jié)點
return getNode(root)
}