Reputation: 88
I was trying to get the currency data from Rest countries API v3.1: https://restcountries.com/v3.1/all. What I was trying to do was get the name of the countries which have United States dollar as it's currency and print it in browser console.
I tried the following code :
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://restcountries.com/v3.1/all")
xhr.send();
xhr.onload = () => {
let data = JSON.parse(xhr.response)
let answer = data.filter((dummy) => (dummy.currencies !== undefined))
let realanswer = answer.filter((dollar) => (dollar.currencies.name === "United States dollar"))
console.log(realanswer)
}
But I am getting an empty array in output with no data in it.
I tried to get the data I need with rest countries api v2: https://restcountries.com/v2/all and got the data I needed with following code:
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://restcountries.com/v2/all")
xhr.send();
xhr.onload = () => {
let data = JSON.parse(xhr.response)
let answer = data.filter((dummy) => (dummy.currencies !== undefined))
let realanswer = answer.filter((dollar) => (dollar.currencies[0].name === "United States dollar"))
console.log(realanswer)
}
So can anyone tell me why I am not getting the data from Rest countries API v3.1? Also I would like to inform that in v2.0 the currency data is stored in an array but in 3.1 it is stored in an object. I can't figure out how to access currencies data with v3.1. Also I want to get the data with the help of filter method only. Please help!
Upvotes: 0
Views: 6326
Reputation: 1
data[0].currencies ? ${ data[0].currencies[Object.keys(data[0].currencies)[0]].name }
: "" ;
Upvotes: 0
Reputation: 23
Answer for stackzebra: Actually you can use this formula:
Object.keys(
data. Currencies
)[0]
for extracting the data from object like this and if there are no other options for currencies you can omit [0] I hope this solve your problem
Upvotes: 0
Reputation: 478
It's because in v3.1 it's not just currencies.name
, it's like this:
Upvotes: 0
Reputation: 71
// Hello Check this out it works absolutely fine
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://restcountries.com/v3.1/all")
xhr.send();
xhr.onload = () => {
let data = JSON.parse(xhr.response)
/* console.log(data) */
let answer = data.filter((dummy) => (dummy.currencies !== undefined))
console.log(answer.length)
let realanswer = answer.filter((data) => {
for (let key in data.currencies) {
if(data.currencies[key].name === "United States dollar"){
return data
}
}
})
console.log(realanswer.length, realanswer[0].currencies)
}
Upvotes: 1