0

This is the simple currency converter script which gets the currency rate from JS library - it's based on the last value in JSON chaining (PLN, EUR etc. ) ->

    var priceAmount = amount;
    var currencyRateUSDPLN = Currency.rates.PLN;

I know that I can't pass the function argument straight to Currency.rates.PLN, what is the shortest way to achieve this functionality ?

function convertCurrency (amount, to) {
    var priceAmount = amount;
    // here I want to pass 'to' argument (EUR, PLN for example)
    var currencyRateUSDPLN = Currency.rates.to;
    var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
    console.log(pricePLN + ' PLN');
}

The Currency object contains -> link

4
  • 1
    what is Currency.rates.PLN? Commented Nov 15, 2017 at 10:00
  • it returns the currency rate from JS library, the value is something about 0.27 Commented Nov 15, 2017 at 10:02
  • Without knowing what the object Currency.rates contains, there's not much we can help with, but shouldn't var currencyRateUSDPLN = Currency.rates.to; just be var currencyRateUSDPLN = to; as you'd be passing the Currency.rates.PLN; to the function? Commented Nov 15, 2017 at 10:02
  • I've updated the question :) Commented Nov 15, 2017 at 10:10

2 Answers 2

3

I'm assuming the question you are trying to ask is how can you use the value of an argument to access an object property.

you can do this using bracket notation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

function convertCurrency (amount, to) {
    var priceAmount = amount;
    // here I want to pass 'to' argument (EUR, PLN for example)

    var currencyRateUSDPLN = Currency.rates[to];
    // If 'to' argument passed in is "EUR" then this
    // will resolve to Currency.rates.EUR

    var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
    console.log(pricePLN + ' PLN');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I meant this exactly :), I'll change the question title for your suggestion. Problem solved!
1

The way to do this is to interpolate the to value via square brackets ([]). So:

Currency.rates[to]

Alternatively, instead of passing strings in to the function and interpolating them, you could just pass the currency rate reference directly:

function convertCurrency (amount, to) {
    console.log(( amount / to ).toFixed(2) + ' PLN');
}

convertCurrency(34.56, Currency.rates.PLN)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.