1

I have the following JSON structure and I need to iterate over the nested values of data.list. I'm able to get a nested value when I hard-code with the following console.log(data["list"][0]["My website is https://www.test.com"][0][0].command);, but not when I try to iterate overall of data.list's objects.

var data = {
    "list": [
        {
            "The first website is https://www.w3.org/": [
                [
                    {
                        "command": "This is dummy content",
                        "new": false,
                        "message": "This was fun to make"
                    }
                ]
            ]
        },
        {
            "The second website is https://www.mozilla.org": [
                [
                    {
                        "command": "This is the second command",
                        "new": true,
                        "message": "Lorem ipsum"
                    }
                ]
            ]
        }
    ],
    "verified": false
};


for (var i = 0; i < data.list.length; i++) {
        // this doesn't work
        console.log(data.list[i][0]["0"]["0"]).command;
}
4
  • do you get any error?
    – Rohan Sood
    Commented Jun 15, 2017 at 18:43
  • 5
    Why would you set a property to an arbitrary string? You really need to rethink your schema. Commented Jun 15, 2017 at 18:43
  • your json is very weird, you have an 1-element array of 1-element array everytime ?
    – ValLeNain
    Commented Jun 15, 2017 at 18:44
  • Do you prefer to implement more generic solution or just specific to your array?
    – HieuHT
    Commented Jun 15, 2017 at 19:50

2 Answers 2

1

You could use the first key in the object.

var data = { list: [{ "The first website is https://www.w3.org/": [[{ command: "This is dummy content", new: false, message: "This was fun to make" }]] }, { "The second website is https://www.mozilla.org": [[{ command: "This is the second command", new: true, message: "Lorem ipsum" }]] }], verified: false },
    i;

for (i = 0; i < data.list.length; i++) {
    console.log( data.list[i][Object.keys(data.list[i])[0]][0][0].command);
}

1

Because the items in the list are objects you have iterate over them in a separate loop. Also, you must take into account that it's an object so you should use the object property as the index and not an integer.

The below should work:

for (var i = 0; i < data.list.length; i++) {
        // this doesn't work
        for (var property in data.list[i]) {
            console.log(data.list[i][property][0][0].command);
        }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.