2016-08-17 219 views
0

我想从JSON对象访问某个值。我尝试访问的值是从具有大量嵌套对象和数组的JSON对象启动 - > rocket-> agencies-> abbrev。出于某种原因,我无法访问某个嵌套级别以下的值。以下是控制台中记录的JSON对象的屏幕截图。访问嵌套的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); 
} 

我可以访问关键:在 “火箭” 的水平值对,但我不能访问嵌套在该级别以下的任何东西。我如何调用数据有什么问题吗?

+0

你的榜样它会工作。所以你最有可能拥有json的一部分,你没有显示哪里代理不在[0]。 https://jsfiddle.net/8oeu7qsm/ – baao

回答

2

从json对象的结构看来,您需要索引关闭机构。代码示例的最后一行应该可以工作。

我可以想象你会希望像

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

这样,如果没有机构的,你不会得到错误

+0

谢谢。语法有点不合适,但是我可以调整它以使其工作!有道理,我需要另一个循环来确定机构对象的索引。 – ncox85

+0

没问题!很高兴我能帮上忙! –

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); 
    }; 
}