Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda