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);
Replace return findObjectById(pageVar, id);
on the
pageSrch = findObjectById(pageVar, id);
if(pageSrch){
return pageSrch;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.