I made a function in order to find an element in a tree object. My function works, but sometimes the function don't find the value and stop before looking all the tree.
I can't explain why it works sometimes and sometimes not.
Here is my fiddle : http://jsfiddle.net/3cdwA/2/
When you click on categories like "Sciences" you can see that it works. But if you click on "Bandes-Dessinées" it should display "Comics" but it doesn't.
Here is my recursive function :
function getChildrenFromCurrentFolder(tree, targetFolder) {
console.log(tree);
// Find recursivly all direct children of targeted folder
if (targetFolder == tree.id) {
return tree.folders;
} else if (tree.folders.length > 0) {
var folders = [];
for (i = 0; folders.length == 0 && i < tree.folders.length; i++) {
folders = getChildrenFromCurrentFolder(tree.folders[i], targetFolder);
}
return folders;
}
return [];
}
here is my test tree :
tree = {
'id': 1,
'name': 'Mes Bookmarks',
'folders': [
{
'id': 2,
'name': 'Sciences',
'folders': [
{
'id': 3,
'name': 'Biologie',
'folders': [
{
'id': 12,
'name': 'Neurologie',
'folders': []
}
]
},
{
'id': 4,
'name': 'Astrophysique',
'folders': [
{
'id': 8,
'name': 'Cosmologie',
'folders': [
{
'id': 10,
'name': 'Système solaire',
'folders': []
}
]
},
{
'id': 9,
'name': 'Trous noirs',
'folders': []
}
]
},
{
'id': 5,
'name': 'Mathématiques',
'folders': []
}
]
},
{
'id': 6,
'name': 'Actualités',
'folders': [
{
'id': 11,
'name': 'Monde',
'folders': []
}
]
},
{
'id': 7,
'name': 'Bandes-dessinées',
'folders': [
{
'id': 13,
'name': 'Comics',
'folders': []
}
]
}
]
};