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

311
Visualizações
JavaScript hard code to loop problem. Setting grandchildren to children to parent

What I thought was going to be simple enough is turning out to be a headache for days. I can get it to work hard-coding it but cannot get it to work in a loop. This is what i have hard-coded.

         let vt = [{animal:"dog"},{color:"green"},{tail:"curly"}];

         vt[0]["children"]={pupname:"harry",pupcolor:"red"}
         vt[0]["children"]["children"]={pupname:"joe",pupcolor:"brown"}
         vt[0]["children"]["children"]["children"]={pupname:"itchy",pupcolor:"black"}

console.log(JSON.stringify(vt));

This will give me what i want.

[{
    "animal": "dog",
    "children": {
        "pupname": "harry",
        "pupcolor": "red",
        "children": {
            "pupname": "joe",
            "pupcolor": "brown",
            "children": {
                "pupname": "itchy",
                "pupcolor": "black"
            }
        }
    }
}, {
    "color": "green"
}, {
    "tail": "curly"
}]

This is a simplified version and there could be many objects in the array. I cant get it to work in a loop. The ever increasing number of children keys is my problem, or maybe i'm way off track anyway. Any pointers welcome

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you can do that:

const vt = [ { animal: 'dog' }, { color: 'green' }, { tail: 'curly' } ];

[ { pupname:'harry', pupcolor:'red'   }
, { pupname:'joe',   pupcolor:'brown' }
, { pupname:'itchy', pupcolor:'black' }
].reduce((a,c)=>a.children = c, vt[0]);

console.log( vt );
.as-console-wrapper {max-height: 100%!important;top:0 }

about 4 years ago · Juan Pablo Isaza Relatório
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