Search code examples
javascriptloopsparentchildren

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


Solution

  • 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 }