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?
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
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);
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.