How to get JSON data with changing part of the call to get that data

Viewed 43

I'm working on a side project of a currency converter. I've made an API Call and this is all the data it sent me (this varies depending on the selected currencies so USD_GBP could be CAD_JPY):

{
    "query": {
        "count": 1
    },
    "results": {
        "USD_GBP": {
            "id": "USD_GBP",
            "val": 0.733695,
            "to": "GBP",
            "fr": "USD"
        }
    }
}

In my express code I've set up the HTTPS Module:

https.get(url, function(response) {

    response.on("data", function(data) {
      const currencyData = JSON.parse(data);
      const exchangeRate = currencyData.results.USD_GBP.val;
    });
  });
});

The problem you can probably see is that since the currency to convert from and convert to are always changing the constant exchangeRate doesn't work for any scenario besides converting from USD to GBP. So I'm wondering how to make that work for every combination that I throw at it. Above my HTTPS get request I already made a variable (const combine = firstCurrency + "_" + secondCurrency;) that combines the selections. I tried concatenating it to the exchangeRate variable, but it gave me an error that it can't find the value of undefined.

3 Answers

JavaScript objects allow you to use bracket notation for dynamic variables names.

var obj = { bar: 'baz'; }
var foo = 'bar';
obj.foo ; // This is invalid, as it looks for the "foo" property
obj[foo]; // This is valid, as it looks for the "bar" property we want

Since you mentioned you have a variable named combine already, you should be able to use bracket notation on the results:

const exchangeRate = currencyData.results[combine].val;

Here's a quick little snippet:

var firstCurrency = 'USD';
var secondCurrency = 'GBP';
const combine = firstCurrency + "_" + secondCurrency;

var response = `{
    "query": {
        "count": 1
    },
    "results": {
        "USD_GBP": {
            "id": "USD_GBP",
            "val": 0.733695,
            "to": "GBP",
            "fr": "USD"
        }
    }
}`;

const currencyData = JSON.parse(response);
const exchangeRate = currencyData.results[combine].val;

console.log( exchangeRate );

If you didn't have the combine variable, you could always use Object.keys() to get the keys from the result and use that, but it's arguably uglier (especially since you already know the key):

const exchangeRate = currencyData.results[Object.keys(currencyData.results)[0]].val;

Instead of currencyData.results.USD_GBP.val, use currencyData.results['USD_GBP'].val

You can even use a variable as well. :

currencies = ['USD_GBP', 'EUR_USD']
currenceis.forEach(currency => {
  currencyData.results[currency].val
}

Changed Example:

https.get(url, function(response) {

    response.on("data", function(data) {
      const currencyData = JSON.parse(data);
      const exchangeRate = currencyData.results['USD_GBP'].val;
    });
  });
});

You can use the backtick syntax.

let firstCurrency = "USD";
let secondCurrency = "GBP";

const currencyData = {
    "query": {
        "count": 1
    },
    "results": {
        "USD_GBP": {
            "id": "USD_GBP",
            "val": 0.733695,
            "to": "GBP",
            "fr": "USD"
        }
    }
};

const exchangeRate = currencyData.results[`${firstCurrency}_${secondCurrency}`].val;

console.log(exchangeRate);

Related