Reputation: 497
I'm testing with an currency conversion API (http://fixer.io/), for now i'm just calling the API to find the exchange rate on the base currency . For now I have hardcoded the base currency in the API url. I'm able to get the exchange rates object but i'm not able to get the specific exchange rate corresponding to the base currency e.g If the base currency is USD and i'm looking the exchange rate in JPY its not displaying the value.
I'm trying to achieve this using JQuery only.
var link1 = "https://api.fixer.io/latest?base=USD";
$.ajax({
type: "GET",
url: link1,
success: function(rates) {
$.each(rates, function(i, exchangeRates) {
if(exchangeRates+"."+ "JPY"){
var z = exchangeRates+"."+"JPY"; //This concat is not working
console.log(z);
}
else{
console.log("error");
}
});
}
});
What am i doing wrong here?
Upvotes: 1
Views: 70
Reputation: 337700
Firstly rates
is an object, so you need to use bracket notation to access it by key. You cannot just append a string to a variable name and use that as an accessor.
Secondly, you don't need to loop over the returned data as it's a nested object. Try this:
var link1 = "https://api.fixer.io/latest?base=USD";
var targetCurrency = 'JPY';
$.ajax({
type: "GET",
url: link1,
success: function(response) {
var rate = response.rates[targetCurrency]; // note bracket notation here
console.log(rate);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1