Home > Software engineering >  Loop inside a nested tree js
Loop inside a nested tree js

Time:07-02

menu:[{
id:''
name:'',
child:'[{
   id:''
   name:'',
   child:'[]'
}]'
}]

This child element is nested infinitely.How to loop over this tree to get data of the passed id of the child?

CodePudding user response:

let obj = {

    menu:[{
        id:1,
        name:'Raj',
        child:[{
           id:2,
           name:'vivek',
           child:[{
            id:3,
            name:'sameer',
            child:[{
                id:4,
                name:'sahil',
                child:[]
                
               }]
            
           }]
        }]
    }]

}

let userInput = 2;
function checkid(obj1){
    let {
        id,
        name:cname,
        child
    } = obj1;
    if(id === userInput){
        return obj1;
    }
    else{
       return checkid(child[0]);
    }
    
    
}
console.log(checkid(obj.menu[0]));

I hope this helps you!!

CodePudding user response:

function handleElement(el){
  if('id' in el){
    // do something with el['id']
  }
  if('child' in el){
    handleElement(el.child)
  }
}
for (const el of menu){
  handleElement(el)
}
  • Related