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/

asked Dec 7, 2015 at 11:40

1 Answer 1

1

Replace return findObjectById(pageVar, id); on the

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

JSFiddle

answered Dec 7, 2015 at 11:51
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.