I have no idea why this little thing returns “undefined” when console.log print correct result. Thx in advance.
App.Presentation.prototype.getLeaf = function(leafSlug, tree) {
for (var key in tree.content) {
if (tree.content[key].type === 'leaf' && tree.content[key].slug === leafSlug) {
console.log(tree.content[key]) // this works Correct
return tree.content[key]; // this returns undefined :<
} else {
this.getLeaf(leafSlug, tree.content[key]);
}
}
};
I’m calling this in console like this:
Presentation.getLeaf("chpl", Presentation.tree);
And getting this result:
(first result from console.log)
Object {type: "leaf", alias: "Chpl bla bla bla", slug: "chpl", group: "", order: ""…}
alias: "Chpl bla bla bla"
group: ""
html: "<img src='bg.png' />"
order: ""
parent: "chpl"
slug: "chpl"
type: "leaf"
__proto__: Object
(next result from return)
undefined
Presentation.tree is a variable containing JSON parsed to object.
If the
tree.contenthas no key where your condition is true, your function neverreturns anything so you get backundefined.And even if some of the recursive calls may
logsomething, their result is not used anywhere. You need to return the result of the recursive call from the calling function as well! Change the else-branch to