Skip to content

Instantly share code, notes, and snippets.

@seveniu
Created December 4, 2015 14:01
Show Gist options
  • Save seveniu/039f111eed4bb4163bd3 to your computer and use it in GitHub Desktop.
Save seveniu/039f111eed4bb4163bd3 to your computer and use it in GitHub Desktop.
javascript list to tree
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