Created
December 4, 2015 14:01
-
-
Save seveniu/039f111eed4bb4163bd3 to your computer and use it in GitHub Desktop.
javascript list to tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ListToTree(data,deep,getChildren) { | |
this.stackListLength = deep -1-1; //不包含 root | |
this.stackList = []; | |
// 初始化 root | |
this.root = {id: 0}; | |
// 初始化 栈 | |
for (var i = 0; i < this.stackListLength; i++) { | |
this.stackList.push([]); | |
} | |
this.start = function () { | |
var firstLevel = getChildren(this.root.id); | |
this.root.children = firstLevel; | |
this.stackList[0].concat(firstLevel); | |
var curStack = 0; | |
Array.prototype.push.apply(this.stackList[curStack], firstLevel); | |
while(this.stackList[0].length != 0) { | |
var temp = this.stackList[curStack].pop(); | |
if(!temp) { | |
curStack--; | |
continue; | |
} | |
var tempChildren = getChildren(temp.id); | |
temp.children = tempChildren; | |
if(tempChildren.length == 0 || curStack == this.stackListLength - 1) { | |
continue; | |
} | |
curStack++; | |
Array.prototype.push.apply(this.stackList[curStack], tempChildren); | |
} | |
return this.root; | |
} | |
} | |
function getChildrenById(id) { | |
return tagList.filter(function (v) { | |
return v.parentId == id; | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment