user1289451 user1289451 - 2 months ago 9
Javascript Question

Issues looping through JSON data in Javascript

My JSON data:

var menu = {"parent":[
{
"id": 1,
"name": "Information",
"child": [
{
"id": 1000,
"name": "Example"
}
]
},
{
"id": 2,
"name": "Something"
},
{
"id": 3,
"name": "Something else",
"child": [
{
"id": 2000,
"name": "Yay"
}
]
}


My JavaScript:

$(document).ready(function () {


var xhr = new XMLHttpRequest();

xhr.open("GET", "https://sable-belief-1704.justapis.io/parentmenu", false);
xhr.send();

var responseJson = JSON.parse(xhr.response);
var responseParent = responseJson.parent;

for(var i in responseParent) {

if (responseParent[i].hasOwnProperty('child'))
{
console.log(responseParent[i]);
console.log(responseParent[i].child[i]);
}
}
});


I'm stumped here. This code works fine for the first object that has a child object. But when it loops to the second object that has a child object, it will run the first console.log and I can see my parent object with the child object on it, but for some odd reason, on the second console.log where I'm trying to log the child object, it will just return undefined. That seems weird to me considering the child object is there when I log the parent object.

Here is a JSFiddle you can run to see what I mean: https://jsfiddle.net/4rcy66r7/

Any ideas?

Answer

This:

    console.log(responseParent[i]);
    console.log(responseParent[i].child[i]);
                                       ^^^

You're using the same index for two completely independent arrays. All of those child arrays only have ONE object in them, always at index 0, but you're trying indexes [1], [2], [3], etc... which simply do not exist.

It should be

    console.log(responseParent[i].child[0]);
                                        ^---

instead.