2017-07-18 169 views
0

我是javascript新手。如何迭代已轉換爲JavaScript對象的JSON結果?迭代JavaScript對象

const url = 'https://api.mybitx.com/api/1/tickers?pair=XBTMYR'; 
    fetch(url) 
    .then(res => res.json()) 
    //.then(json => console.log(json)) 
    .then(function(data) { 
    let bp = data.tickers 
    console.log(bp.timestamp) 
    }) 

對象結果

[ { timestamp: 1500349843208, 
    bid: '9762.00', 
    ask: '9780.00', 
    last_trade: '9760.00', 
    rolling_24_hour_volume: '325.277285', 
    pair: 'XBTMYR' } ] 

我只是想打印出來的 「時間戳」 鍵。謝謝。

+0

嘗試data.timestamp –

+0

返回「undefined」 –

+0

[如何訪問JavaScript數組中的元素?](https://stackoverflow.com/questions/15995780/how-to-access-a-element-在JavaScript的陣列) – user3351605

回答

2

把鑰匙,然後對象。

console.log(bp[0].timestamp) 
0

你的結果是一個數組,因爲這樣就可以通過索引或通過使用for.forEach迭代它。

for(var i=0; i<bp.length;i++) { 
    var element= bp[i]; 
} 

數組中的每個元素都是一個對象。要訪問該元素的時間戳使用["timestamp"].timestamp

for(var i=0; i< bp.length; i++) { 
    var element = bp[i]; 
    var timestamp = element.timestamp; 
    var ts= element["timestamp"]; 
} 

爲了得到第一個時間戳使用簡單地使用b[0].timestamp