0

I am trying to obtain the price of a currency a user has selected. The way I am doing this is querying an API which returns a JSON object with a key named after the specific currency. So for USD it returns an object that looks like:

{"nano":{"usd":5.14}}

The problem is that if the user changes the currency, the key name changes aswell:

{"nano":{"gbp":5.14}}

To access the value I was using data.nano.usd however I'd have to write a statement for every currency to do it this way. I tried creating a currency variable and using data.nano.currency but this didn't work because the key is not named currency.

How can I create an accessor which can be changed based on user input?

  • [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Andreas Mar 06 '21 at 10:40

1 Answers1

0

You just need to make the object key variable. In an object his can be done using [var]

function currencyObject(currency)
{
return{"nano":{[currency]:5.14}};
}

console.log(currencyObject('usd'));

getting the value:

function getCurrency(currency)
{
  let currencies = {"nano":{"usd":5.14}};
  
  return currencies.nano[currency];
}

console.log(getCurrency('usd'));
SuperDJ
  • 7,108
  • 9
  • 38
  • 68