javascriptarraysjsonfixer.io

Why does JSON not accept item from array?


I wanna request the exchange rates from an API for every currency by using an array filled with the available currencies.

My JavaScript Code:

var requestURL = 'https://api.fixer.io/latest';

var requestUrlstandard = 'https://api.fixer.io/latest';
var request = new XMLHttpRequest();

request.open('GET', requestURL);
request.send();
request.onload = function() {

    var obj = JSON.parse(request.response);
    var currencies = ["AUD", "BGN", "BRL", "CAD", "CHF", "CNY", "CZK", "DKK", "GBP", "HKD", "HRK", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "PHP", "PLN", "RON", "RUB", "SEK", "SGD", "THB", "TRY", "USD", "ZAR"]
    var lol = currencies[0]

    console.log(obj)
    console.log(currencies[0])
    console.log(lol)
    console.log(obj.rates.AUD)
    console.log(obj.rates.lol)

The console output:

console output

The expanded output of the JSON:

expanded output of the JSON


Solution

  • Because lol is a variable name containing a string value you need to use object bracket notation to retrieve that value from the rates array.

    obj.rates[lol]