BTC75
BTC75

Reputation: 91

Open Exchange Rates issue to define currency from variable

I am fetching a specific currency exchange rate on a specific date through the API in javascript. My code goes like:

 var currency = 'KWD';
 var date = '2022-01-01';
 $.get('https://openexchangerates.org/api/historical/' + date + '.json', {app_id: 'XXXXXXXXXXX'}, function(data) {
alert("On " + date + ", 1 US Dollar was worth " + data.rates.currency + " "+currency);
           });

all works well if I specify the final currency in my code:

 $.get('https://openexchangerates.org/api/historical/' + date + '.json', {app_id: 'XXXXXXXXXXX'}, function(data) {
alert("On " + date + ", 1 US Dollar was worth " + data.rates.KWD + " "+currency);
           });

but i need to fetch the currency from variable currency. any help on this?

Upvotes: 0

Views: 147

Answers (1)

Delta
Delta

Reputation: 521

As Shreshth stated in a comment above, you can use square brackets to access object properties from a variable's content.

For example...

$.get('https://openexchangerates.org/api/historical/' + date + '.json', {app_id: 'XXXXXXXXXXX'}, function(data) {
    alert("On " + date + ", 1 US Dollar was worth " + data.rates[currency] + " "+currency);
});

Upvotes: 1

Related Questions