我正在尝试从JSON对象访问某个值。我试图访问的值是从具有大量嵌套对象和数组的JSON对象启动 - > rocket-> agencies->缩写。由于某种原因,我无法访问某个嵌套级别以下的值。以下是控制台中记录的JSON对象的屏幕截图。
JSON Object screenshot http://prntscr.com/c6ym11 修改:Link to the image, since embedding didn't work
Here is a link to an example of the JSON formatting in the returned data
这些是我尝试的方式:
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);
}
我可以在&#34; rocket&#34;上访问key:value对。级别,但我无法访问嵌套在该级别下的任何内容。我如何调用数据有什么问题吗?
答案 0 :(得分:2)
从json对象的结构看起来你需要一个代理商的索引。代码示例的最后一行应该有效。
我想你会想要像
这样的东西for(j = 0; j < data.launches[i].rocket.agencies.length; j++){
agency.push(data.launches[i].rocket.agencies[j].abbrev);
}
这样,如果没有代理商,您将不会收到错误
答案 1 :(得分:0)
这是有用的:
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);
};
}