0

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.

4
  • Your push should work...what variable is this stored in? Commented Jun 11, 2014 at 12:50
  • I deleted my answer, as it is unclear to me what Planes exactly is, please name your variables in your example so that we can work it out. Commented Jun 11, 2014 at 13:34
  • Lol. Your answer actually worked. Turns out that in the new array, "Groups" actually wasn't defined. So, I just gave an empty "group" element, and it worked. Commented Jun 11, 2014 at 13:58
  • I undeleted my answer Commented Jun 11, 2014 at 14:02

1 Answer 1

2

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" });
Sign up to request clarification or add additional context in comments.

4 Comments

groups[0].groups[0].groups.push({label: json.groups[0].groups[0].groups[0].label}) says that "groups[0].groups[0].groups is undefined". As in the JSON is correct, the function is incorrect.
What I meant is to access from your object, I'll update my answer to clarify
Let me further clarify. I had made a new array called as "Planes". I was pushing to the "Data Plane" label via Planes.push({label : $LABEL_AQUIRED_FROM_JSON$}). I tried your method now. Planes.groups[0].groups[0].groups.push({label: "Data5"}] I still get Planes.groups is undefined.
Oh Planes.groups[0].groups.push then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.