Shafiq Mustapa
Shafiq Mustapa

Reputation: 433

iterate JavaScript object

I am new to javascript. How do I iterate a JSON result that has convert into javascript object?

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

the object results are

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

I just want to print out the "timestamp" key. Thanks.

Upvotes: 0

Views: 51

Answers (2)

Alexander Higgins
Alexander Higgins

Reputation: 6923

Your result is an array, as such you can iterate it by index or by using for or .forEach.

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

Each element in your array is an object. To access the timestamp of that element use ["timestamp"] or .timestamp

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

To get the first time stamp use simply use b[0].timestamp.

Upvotes: 0

Shafiq Mustapa
Shafiq Mustapa

Reputation: 433

Put key and then the object.

console.log(bp[0].timestamp)

Upvotes: 2

Related Questions