Reputation: 323
Hi I have dynamic tree data like below containing children, may increase the like tree8,tree9 node and children how can I find the name of the node that had the last child and all id's, As I said, this tree structure can continue dynamically. answer for the example below last child node name tree4, and all tree is = ["1","2","3","4","5","6","7"] The important point here is that I cannot find how to do it when dynamic data arrives, thanks for suggestion
let tree = {
id: 1,
name: "tree1",
children: [
{
id: 2,
name: "tree2",
children: [
{
id: 4,
name: "tree4",
children: [
{
id: 6,
name: "tree6"
},
{
id: 7,
name: "tree7"
}
]
},
{
id: 5,
name: "tree5"
}
]
},
{
id: 3,
name: "tree3"
}
]
};
Upvotes: 1
Views: 594
Reputation: 175
You can use recursive function
// Based on your question and solution , I can see that you want to check only children[0] object for children.
let noChildParent;
let id = [];
let checkIfChildrenExist = (prop,parentName) =>{
//console.log(prop,noChildrenParent);
if(prop.children == null)
{
noChildParent = parentName;
return
}
checkIfChildrenExist(prop.children[0],prop.name); \\ recursive pattern
}
let checkId = (prop)=>{
//console.log(prop.id);
id.push(prop.id);
if(prop.children == null) return;
prop.children.forEach((el)=>{
checkId(el);
});
}
checkIfChildrenExist(tree);
checkId(tree);
console.log("noChildParent",noChildParent, "ID",id); // tree4 // [1, 2, 4, 6, 7, 5, 3]
//You can sort id array if you want it to be in specific order
Upvotes: 2