0

I have the following recursive function but it doesnt work... It searches as far down as 'firstPageChild' and then finishes. Can anyone spot what is wrong here?.. I'm sure its something simple but its stumping me at the moment..

  var pageMap = [{"pageID" : "mainPage",
                        "children": [{"pageID" : "firstPage",
                                   "children": [{"pageID" : "firstPageChild",
                                                 "children": []
                                                }]
                                    },
                                    {"pageID" : "secondPage",
                                   "children": [{"pageID" : "secondPageChild1",
                                                 "children": []
                                                }, {"pageID" : "secondPageChild2",
                                                 "children": []
                                                }]
                                    },
                                    {"pageID" : "thirdPage",
                                   "children": [{"pageID" : "thirdPageChild1",
                                                 "children": []
                                                }, {"pageID" : "thirdPageChild2",
                                                 "children": []
                                                }]
                                    }]
                      }];

function findObjectById(root, id) {
debugger;
var k, pageVar;
if (root.children) {
    for (k in root.children) {

        pageVar = root.children[k];

        if (pageVar.pageID == id) {
            return pageVar;
        }
        else if (pageVar.children.length) {
            return findObjectById(pageVar, id);
        }
    }
}
};

for (var i = 0, len = pageMap.length; i < len; i++) {
  var myObj = findObjectById(pageMap[i], "secondPageChild2");
}


console.log(myObj);

http://jsfiddle.net/3nkfbbyy/

1 Answer 1

1

Replace return findObjectById(pageVar, id); on the

pageSrch = findObjectById(pageVar, id);
if(pageSrch){
   return pageSrch;
}

JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.