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

120
Views
Method/pattern to check for objects and place them as nested objects if criteria met

I have an account object with children accounts (rootAccount). I am trying to write some logic that will take the rootAccount object and search the children accounts to see if they are parents of any accounts. If so, then those accounts will be added to the children account in a new property for the account called children. It becomes a little more complex because each new account can possibly have child accounts and likewise be added as a new property to the account. So this will keep nesting objects possibly until there are no more children accounts.

Is there a common pattern/method to use for this scenario? I can get about as far as filtering out the object that is the parent but I'm not sure how to add it to the rootAccount object and then loop this logic so it will check for new children accounts and keep adding nested children accounts.

   var childAccount = [{Name: "Johnson Little Plastics", Id: '4', parentAccount: '3'}];


   var rootAccount = {
     Name: "Johnson Holding Company",
     Id: '1',
     children: [
       {Name: "Johnson Metals", Id: '2', parentAccount: '1'},
       {Name: "Johnson Plastics", Id: '3', parentAccount: '1'}
       ]
     }


     for(var x of childAccount){
         var f = rootAccount.children.filter((account,i) => {
         return account.Id == x.parentAccount;
     });

     console.log(f[0].Id);
     }

What it will look like after it runs through:

   var rootAccount = {
     Name: "Johnson Holding Company",
     Id: '1',
     children: [
       {Name: "Johnson Metals", Id: '2', parentAccount: '1'},
       {Name: "Johnson Plastics", Id: '3', parentAccount: '1',
        children: [{Name: "Johnson Little Plastics", Id: '4', parentAccount: '3'}]
       }
       ]
     }
about 4 years ago · Juan Pablo Isaza
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!