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.
montrealist
5,71812 gold badges50 silver badges72 bronze badges
asked Jul 18, 2017 at 4:04
Shafiq Mustapa
4333 gold badges7 silver badges17 bronze badges
-
Try data.timestampYogen Darji– Yogen Darji2017年07月18日 04:08:30 +00:00Commented Jul 18, 2017 at 4:08
-
return "undefined"Shafiq Mustapa– Shafiq Mustapa2017年07月18日 04:14:32 +00:00Commented Jul 18, 2017 at 4:14
-
Possible duplicate of How to access a element in JavaScript array?user3351605– user33516052017年07月27日 12:00:19 +00:00Commented Jul 27, 2017 at 12:00
2 Answers 2
Put key and then the object.
console.log(bp[0].timestamp)
answered Jul 18, 2017 at 4:18
Shafiq Mustapa
4333 gold badges7 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Jul 18, 2017 at 4:18
Alexander Higgins
6,9341 gold badge30 silver badges45 bronze badges
Comments
lang-js