0

I'm using a $.each statement to loop through JSON and after creating the object, it's being displayed correctly on the console.log, but says it has no keys. Below are the methods being used and the console.log output.

JS: (This is in a $.extend(Account.prototype) to create the methods

getDuration: function(type){
    var data = {},
        type = type;

    $.get('/service/account/ajaxdata?method=duration&type='+type, function(response){
        console.log(response);
        $.each(JSON.parse(response), function(k,v){
            data[v.type] = v.duration;
        });
    });
    return data;
},

getUserRates: function(){
    var duration = this.getDuration('user');

    console.log(duration);       
    console.log(duration['ADDUSER']); 
}

Below is the output of the console.log function

response:
[{"name":"SUBSCRIPTION","duration":"30","id":"2","type":"BASICSUB","lightning_radius":null,"description":"Basic Subscription"},{"name":"ADDUSER","duration":"30","id":"3","type":"ADDUSER","lightning_radius":null,"description":"Additional User(s)"}]

duration:
Object
     ADDUSER : "30"
     BASICSUB : "30"

duration['ADDUSER']:
undefined

And just for the sake of it, Object.keys(duration) returns {}, a blank object. Where am I messing up to grab the value of ADDUSER key?

Jai Chauhan
  • 4,035
  • 3
  • 36
  • 62
jamadri
  • 926
  • 3
  • 17
  • 32
  • I'm confused as to how that existing question answers why I'm getting an undefined value from an object key. If you could explain where on that question this get's answered. – jamadri Nov 10 '16 at 20:33
  • You are accumulating your `data` object inside the callback passed to `$.get()`. That callback will not be invoked until the HTTP request triggered by `$.get()` completes, but the call to `$.get()` itself completes immediately. Therefore, your code reaches the `return` statement long before any actual response data has been received. JavaScript APIs like that are known as **asynchronous** APIs. – Pointy Nov 10 '16 at 20:35

0 Answers0