I have following array with parent and its children. Level of parent and child is not fixed here. The count may vary and there can be more increase in depth of the tree:
[{
"title": "26 - India",
"tooltip": "26 - India",
"children": [
{
"title": "026 - MH",
"tooltip": "026 - MH",
"children": [
{
"title": "2018",
"tooltip": "2018",
"children": []
}
]},
{
"title": "026 - GJ",
"tooltip": "026 - GJ",
"children": [
{
"title": "2018",
"tooltip": "2018",
"children": []
}
]},
{
"title": "026 - UP",
"tooltip": "026 - UP",
"children": [
{
"title": "2018",
"tooltip": "2018",
"children": []
}
]}
]},
{
"title": "27 - USA",
"tooltip": "27 - USA",
"children": [
{
"title": "027 - SA",
"tooltip": "027 - SA",
"children": [
{
"title": "2018",
"tooltip": "2018",
"children": []
}]
}]
}]
and looking for a result like :
26 - India & 026 - MH & 2018
26 - India & 026 - GJ & 2018
26 - India & 026 - UP & 2018
27 - USA & 027 - SA & 2018
where details of all the children with there parent will be shown. I am trying to use the following code to get the result :
var title= "";
searchTree(tree);
function searchTree(tree) {
tree.map(function(item){
if(item.children.length >0){
title = title + " & "+ item.title;
searchTree(item.children)
}
else{
title = title + " & " + item.title;
console.log(title);
title = "";
}
})
}
But this results as follows :
& 26 - India & 026 - MH & 2018
& 026 - GJ & 2018
& 026 - UP & 2018
& 27 - USA & 027 - SA & 2018
The parent with more than one child is not recorded here.
Any help would be appreciated. Thanks in advance!