Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
Loop inside a nested tree js
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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!!

about 4 years ago · Juan Pablo Isaza Report

0

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)
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!