Skip to content

Instantly share code, notes, and snippets.

@tugboat
Created November 10, 2012 01:57
Show Gist options
  • Save tugboat/4049494 to your computer and use it in GitHub Desktop.
Save tugboat/4049494 to your computer and use it in GitHub Desktop.
Recursive function for parsing a tree and building some HTML
var tree = {
a : {value : "This is node A", parent : ""},
b : {value : "This is node B", parent : "a"},
c : {value : "This is node C", parent : "a"},
d : {value : "This is node D", parent : "c"},
e : {value : "This is node E", parent : "c"},
f : {value : "This is node F", parent : "c"}
}
var buildTree = function (obj, node) {
var treeString = "<ul><li>" + obj[node].value;
for (var i in obj) {
if (obj[i].parent == node) {
treeString += buildTree(obj, i);
}
}
treeString += "</li></ul>";
return treeString;
}
document.getElementById("tree").innerHTML = buildTree(tree, "a");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment