0

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 http://prntscr.com/c6ym11 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?

1
  • With your example json it would work. So you most likely have a part of json that you didn't show where agencies[0] is not there. jsfiddle.net/8oeu7qsm Commented Aug 17, 2016 at 18:17

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Syntax is a little off, but I was able to tweak it enough to make it work! Makes sense that I need another loop to determine the index of the agencies object.
No problemo! Glad I could help!
0

This is what worked:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.