2017-01-14 19 views
0

只是想知道,我將如何能夠以以下格式遍歷我的json對象?如何從vanillajs中的json內部的對象中選擇一個字段?

[ 
 
    {"page":1,"pages":1,"per_page":"600","total":264}, 
 
    [ 
 
    { 
 
     "indicator": 
 
    {"id":"NY.GDP.MKTP.CD","value":"GDP (current US$)"}, 
 
     "country":{"id":"1A","value":"ArabWorld"}, 
 
     "value":"2565871160292.11","decimal":"0","date":"2015" 
 
    }, 
 
    { 
 
     "indicator": 
 
     {"id":"NY.GDP.MKTP.CD","value":"GDP (current US$)"}, 
 
     "country":{"id":"S3","value":"Caribbean small states"}, 
 
     "value":"66935278418.3676","decimal":"0","date":"2015" 
 
    }, 
 
    { 
 
     "indicator": 
 
     {"id":"NY.GDP.MKTP.CD","value":"GDP (current US$)"}, 
 
     "country":{"id":"B8","value":"Central Europe and the Baltics"}, 
 
     "value":"1281495024762.4","decimal":"0","date":"2015" 
 
    } 
 
    ] 
 
]

我有這個方法返回的JSON對象

countries: function() { 
 
const URL = 'http://api.worldbank.org/countries/all/indicators/NY.GDP.MKTP.CD?date=2015:2015&per_page=600&format=json' 
 
let countries = [] 
 
fetch(URL).then(i => i.json()).then(j => countries.push(...j)) 
 
console.log(countries); 
 
}

因此,舉例來說,我如何將能夠選擇date場?

感謝 -B

+0

[訪問/處理(嵌套的)對象,數組或JSON]的可能的複製(http://stackoverflow.com/q/11922383/218196)。但是這可能會幫助更多:[如何從異步調用返回響應?](http://stackoverflow.com/q/14220321/218196)。 –

回答

1

要選擇一些深度嵌套,如日期字段,你將訪問它像>

countries[1][0].date 

在其第二個索引[0]可能是你對任何索引數據數組。

檢查它here與數據

+0

這正是我的想法。但我得到以下錯誤'未捕獲的類型錯誤:無法讀取未定義的屬性'0' – WorldWideBangers

+0

我添加了一個示例。並改變了數據,因爲指標不是正確的領域。 – FabioCosta

+1

@WorldWideBangers:您的'console.log(國家)'**在接收到響應之前執行**,因此我假設您在收到響應之前嘗試訪問「國家/地區」。你應該閱讀[我如何返回來自異步調用的響應?](http://stackoverflow.com/q/14220321/218196) –

相關問題