1

Using an Ajax.get, I'm receiving a JSON object and able to access the property I need if I do this

console.log(data.quotes.USDEUR)

However, since the last property changes via user user input, I declared a variable to take it's place and it's showing as undefined:

var destinationCurrency = "USDEUR"  //It can change into "USDAUD, USDGBP, etc"
console.log(data.quotes.destinationCurrency)  // produces undefined

Been looking for a while online. Also tried string concatenation then JSON.parse, but no luck, can anyone help?
Below is the ajax call and console.log.

  function convert() {
        $.get("http://apilayer.net/api/live?access_key=" + key + "&from=" + 
sourceCurrency + "&to=" + destinationCurrency)
            .done(function (data) {
                console.log(data)  //returns JSON
                console.log(data.quotes.USDEUR + "  This works!") //this works
                console.log("typeof - " + typeof(data.quotes.USDEUR))
                var destinationCurrency = "USDEUR"

                console.log(data.quotes.destinationCurrency + "  This doesn't work")
                console.log("typeof = " +typeof(data.quotes.destinationCurrency))
            })
            .fail(function (e) {
                alert(e)
            })
    }

from console log

{success: true, terms: "https://currencylayer.com/terms", privacy: 
"https://currencylayer.com/privacy", timestamp: 1535062191, source: 
"USD", …}privacy: "https://currencylayer.com/privacy"quotes: {USDAED: 
3.6732, USDAFN: 72.655033, USDALL: 108.999898, USDAMD: 483.674987, USDANG: 
1.84685, …}source: "USD"success: trueterms: 
"https://currencylayer.com/terms"timestamp: 1535062191__proto__: Object
currencyConverter.js:19 0.86644  This works!
currencyConverter.js:20 typeof - number
currencyConverter.js:23 undefined  This doesn't work
currencyConverter.js:24 typeof = undefined
gamaterski
  • 11
  • 1
  • `console.log(data.quotes[destinationCurrency])` will work – Jaromanda X Aug 23 '18 at 23:21
  • [see this documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) for how to work with objects - it covers your situation [in this section](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties) – Jaromanda X Aug 23 '18 at 23:25

0 Answers0