简体   繁体   中英

How do I push elements into a nested array in javascript?

Here's what my JSON looks like

{
    "groups": [{
        "label": "Data Plane",
        "groups": [{
            "label": "Compliance Data %",
            "groups": [{
                "label": "Data1"
            }, {
                "label": "Data2"
            }, {
                "label": "Data3"
            }, {
                "label": "Data4"
            }]
        }]
    }]
}

I have parsed this JSON in my JS, and, I have managed to push the Data Plane into a new array. I would also like to push the labels Compliance Data % and the labels Data1 , Data2 , and Data3 into the same array in the same tree format as that of the JSON.

I tried the groups[0].groups[0].groups[0].push function to push to the inner most label. But that doesn't work. I have already extracted the JSON object label and fed it to another array, and I'm trying to push these values. I would like to know how to push it to a new array IN the same structure.

This can't work because you are trying to push into an object literal, try this instead

var o = {
    "groups": [{
        "label": "Data Plane",
        "groups": [{
            "label": "Compliance Data %",
            "groups": [{
                "label": "Data1"
            }, {
                "label": "Data2"
            }, {
                "label": "Data3"
            }, {
                "label": "Data4"
            }]
        }]
    }]
};

o.groups[0].groups[0].groups.push({ label: "Data5" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM