I am trying to render a tree like hierarchy while recursing through set a nodes (index). I already know the roots(top). There are multiple root elements. I am trying to collect the entire html in the variable tree (this entire html will be appended to a div later)
tree = "";
top = ["1", "11", "14", "17", "72", "73", "74", "78", "79", "98", "99"];
index = {
1: {
'name': "Node 1",
'children': "2,3,4,5,6,7,8,9,10"
},
2: {
'name': "Node 2",
'children': ""
},
//.... goes all the way upto 99
}
The recursive function makeFT(index,roots) only seems to break after traversing the children of first element in the "top" array.
The code for this is at jsbin and below. What could be the problem? Is there a better way to do this? Any help is appreciated.
makeFT(index, top);
function makeFT(index, roots) {
console.log(roots);
tree == "" ? tree += '<ul>' : tree += '<ul><hr/>'
for (i = 0; i < roots.length; ++i) {
n = parseInt(roots[i]);
//console.log(n);
//console.log(index[n]);
tree += '<li>' + roots[i] + '</span>' + index[n].name;
if (index[n].children === "") {
tree += '<input class="leaf tree-first-input" type="text" size="2">'
}
else {
tree += '<input class="non-leaf tree-first-input" type="text" size="2">'
makeFT(index, index[n].children.split(","));
}
tree += "</li>"
}
tree += '</ul><br/>'
}
UPDATE : Turns out this is a scoping problem and not a recursion problem. The recursion was alright. Since I did not define scope of the variable 'i' while looping through roots array, each subsequent recursed function inherited the value of unscoped 'i' thereby creating the problem.