Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

309
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda