ncox85 ncox85 - 10 months ago 67
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

//This also works

//This returns undefined

//This generates Uncaught TypeError: Cannot read property 'abbrev' of undefined

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?


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++){

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