樹結構(有id和pid欄位)陣列,生成多層巢狀的json物件
阿新 • • 發佈:2019-02-19
/*
* 傳入的陣列有id和父節點pid欄位,通過它們的關聯構造成一棵或多棵樹結構
* @param nodes 集合
* @param treeRootId 根節點的id
*/
function createTreeData(nodes, treeRootId) {
var groups = {};
// 按父節點將節點分組
for (var i in nodes) {
if (!groups[nodes[i].pid]) {
groups[nodes[i].pid] = [];
}
groups[nodes[i].pid].push(nodes[i]);
if (treeRootPid && treeRootPid === nodes[i].id) { // 發現傳入的根節點id作為節點id時,將根節點設定為該節點的父節點
treeRootPid = nodes[i].pid;
}
}
var rootNodes = groups[treeRootPid];
groups[treeRootPid] = null; // [SAFEGUARD]防止自為父節點或互為父節點(有環圖結構)導致的死迴圈
function traverseTreeNodeGroup(treeNodeGroup) {
for (var i in treeNodeGroup) {
var node = treeNodeGroup[i];
if (groups[node.id]) {
node.children = groups[node.id];
groups[node.id] = null; // [SAFEGUARD]防止自為父節點或互為父節點(有環圖結構)導致的死迴圈
traverseTreeNodeGroup(node.children);
}
}
}
traverseTreeNodeGroup(rootNodes);
return rootNodes;
}
// 測試陣列
var nodes = [
{id: '01', pid: '0'},
{id: '02', pid: '0'},
{id: '011', pid: '01'},
{id: '012', pid: '01'},
{id: '021', pid: '02'},
{id: '022', pid: '02'},
{id: '0221', pid: '022'},
{id: '0222', pid: '022'}
];
// 呼叫
createTreeData(nodes, '0');
/* 返回如下結構
[
{
"id": "01",
"pid": "0",
"children": [
{
"id": "011",
"pid": "01"
},
{
"id": "012",
"pid": "01"
}
]
},
{
"id": "02",
"pid": "0",
"children": [
{
"id": "021",
"pid": "02"
},
{
"id": "022",
"pid": "02",
"children": [
{
"id": "0221",
"pid": "022"
},
{
"id": "0222",
"pid": "022"
}
]
}
]
}
]
*/