樹轉list
/** * 樹轉list */ function treeToList(tree){ for(var i in tree){ var node = tree[i]; list = []; //結果lsit if (node.children.length !== 0) { //遍歷樹的第一層,只有一個根結點 //第一層加入到list中,因為根結點模塊設置為虛擬結點,所以不用加入 /*list.push({ id: node.id, name: node.title, parentId:node.parentId });*/ toListDF(node.children, list, node.id); //遍歷子樹,並加入到list中. } } return list; } /** * 深度優先遍歷樹 * 一個遞歸方法 * @params tree:要轉換的樹結構數據 * @params list:保存結果的列表結構數據,初始傳list = [] * @params parentId:當前遍歷節點的父級節點id,初始為null(因為根節點無parentId) **/ function toListDF (tree, list, parentId) { for (var i in tree) { //遍歷最上層 //將當前樹放入list中 var node = tree[i]; list.push({ id: node.id, name: node.title, parentId:parentId }); //如果有子結點,再遍歷子結點 if (node.children.length !== 0) { toListDF(node.children, list, node.id) //遞歸 } } }
