0

I'm trying to learn more about JSON and I'm messing around with the fixer.io API.

I'm creating a script that will convert currencies. I know how to make the request and get the information but I'm having a little trouble making it dynamic. Below is my script that will pull GBP in comparison to USD.

$('#submitButton').on('click', function(e) {
    e.preventDefault();
    var amount = $('#amount').val();
    var convertFrom = $('#convertFrom').text();
    var convertTo = $('#convertTo').text();

    var requestString = "http://api.fixer.io/latest?base=" + convertFrom;

    $.getJSON(requestString, function(result) {
        var resultString;
        var rate = result.rates.GBP;

        resultString = (amount * rate).toFixed(2);

        $('#results').html(resultString);
        $('#results').removeClass('hide');

    });

This is the line that does the magic, obviously:

var rate = result.rates.GBP;

You can change the currency by replacing GBP with any of the supported currencies, such as EUR for example:

var rate = results.rates.EUR;

What I want to do is substitute "GBP" with a variable such as this (which doesn't work):

var currency = "EUR";
var rate = results.rates.currency;

How can I do this with a variable like attempted above? I know there is an answer out there but I don't know what search terms to use to find my answer.

Thank you very much!

Tanner
  • 11
  • 1
  • Use [Bracket notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Bracket_notation) `var rate = results.rates[currency];` – Satpal Dec 08 '16 at 07:00
  • Note that JSON is the *string* format that you retrieve via Ajax, but jQuery parses that JSON to create an *object,* which is what it passes to your function in the `result` variable. So the `result.rates.GBP` thing that you're doing has nothing to do with JSON, you're asking about how to access object properties. – nnnnnn Dec 08 '16 at 07:03

0 Answers0