I’m having a recursion problem in Javascript. I have some JSON that I’m passing to a function. I’m trying to turn it from JSON into Javascript objects. My problem is that the code only returns the FIRST CHILD, not the second (which is labeled ‘dir3’). Does anyone have a suggestion? Thanks very much for your time.
JSON input:
var dirList = {"name": "topdir", "subdirs":
[
{"name": "dir2", "subdirs":
[
{"name": "dir2a", "subdirs": []},
{"name": "dir2b", "subdirs": []}
]},
{"name": "dir3", "subdirs": []}
]}; //valid JSON
Javascript function:
getChildren = function(dir) {
dir.children = [];
if (dir.subdirs.length == 0) {
return [];
} else {
for (i=0; i<dir.subdirs.length; i++){
dir.children.push({text: dir.subdirs[i].name, leaf: false, expanded: true, children: getChildren(dir.subdirs[i])});
}
return dir.children;
}
};
Make sure you declare the counter in the for loop as a local variable within the function.
It was using a global variable
i, which was causing the loop to end early (one of the other passes through the function had set it to 0).