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

308
Views
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 answers
Answer question

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