ncox85 ncox85 - 3 months ago 18
Javascript Question

Accessing nested JSON value

I am trying to access a certain value from a JSON object. The value I am trying to access is launches->rocket->agencies->abbrev from a JSON object that has a lot of nested objects and arrays. I can't access values below a certain nested level for some reason. Here is a screenshot of the JSON object logged in the console.

JSON Object screenshot
Edit: Link to the image, since embedding didn't work

Here is a link to an example of the JSON formatting in the returned data


These are the ways I have tried:

data = JSON.parse(data);
var agency = [];
var names = [];
var configuration = [];

for(i = 0; i < data.launches.length; i++){
//This works just fine
names.push(data.launches[i].name);

//This also works
configuration.push(data.launches[i].rocket.configuration);

//This returns undefined
agency.push(data.launches[i].rocket.agencies.abbrev);

//This generates Uncaught TypeError: Cannot read property 'abbrev' of undefined
agency.push(data.launches[i].rocket.agencies[0].abbrev);
}


I can access key:value pairs on the "rocket" level, but I cannot access anything nested below that level. Is there something wrong with how I am calling the data?

Answer

From the structure of the json object it looks like you need an index off of the agencies. The last line of your code example should work.

I would imagine you would want something like

for(j = 0; j < data.launches[i].rocket.agencies.length; j++){
  agency.push(data.launches[i].rocket.agencies[j].abbrev);
}

This way if there are no agencies you will not get the error

Comments