how to find n number of nodes have child or cildren
for that we use recursive function
const data = {
'id':'0',
'name':'Tst',
'children':[
{
'id':'1',
'name':'Child - 1'
},
{
'id':'5',
'name':'Child - 5',
'children':[
{
'id':'6',
'name':'Child - 6',
'children':[
{
'id':'7',
'name':'Child - 7',
'children':[
{
'id':'8',
'name':'Child - 8'
}
]
}
]
}
]
}
]
}
const data1 = {
'id':'0',
'name':'Tst',
'children':[
{
'id':'1',
'name':'Child - 1'
},
{
'id':'5',
'name':'Child - 5',
'children':[
{
'id':'6',
'name':'Child - 6',
'children':[
{
'id':'7',
'name':'Child - 7',
'children':[
{
'id':'8',
'name':'Child - 8'
}
]
}
]
}
]
},
{
'id':'9',
'name':'Child - 9',
'children':[
{
'id':'10',
'name':'Child - 10',
'children':[
{
'id':'11',
'name':'Child -11',
'children':[
{
'id':'12',
'name':'Child - 12'
}
]
}
]
}
]
}
]
}
function callChild(data,ParrentArray)
{
if(data.hasOwnProperty('children')){
ParrentArray.push(data.id);
data.children.forEach(x=>{
callChild(x,ParrentArray);
});
}
}
const recursive=(data)=>{
const ParrentArray=[];
callChild(data,ParrentArray);
return ParrentArray;
}
console.log('this is data:',recursive(data));
console.log('this is data1:',recursive(data1));
No comments:
Post a Comment
Thank You For Your Great Contribution