0

I have an Object that contains an associative array

enter image description here

The value stored in the array is an Object

Within the each function, I want to access one of the values in the value object (responseText)

enter image description here

My code is as follows

 var apiNameArray = getDataSourceApiNames();
        var apiResults = {};
        var deferred;

        for (let i = 0; i < apiNameArray.length; i++) {
            var apiName = apiNameArray[i];
            console.log("apiName = " + apiName);
            deferred = $.ajax({
                    type: "GET",
                    url: api_URL + "memberdetails/" + memberNumber,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                }
            );
            apiResults[apiName] = deferred;
        }

        $.when.apply($, apiResults).then(function () {
            console.log(apiResults);
            $.each(apiResults, function (key, value) {
                console.log(key);
                console.log(value);
                console.log(value.responseText);
           });
        });

For some reason, value.responseText is returning undefined. How am I suppose to be accessing this value/property? I have tried value["responseText"], apiResults[key].responseText all with no success

Mike
  • 2,391
  • 6
  • 33
  • 72

1 Answers1

1

As the apiResults is a object you can loop though the keys and use apiResults[key].responseText to access the value.

$.when.apply($, apiResults).then(function () { $.each(apiResults, function (key, value) { console.log(apiResults[key].responseText); }); });

or

$.when.apply($, apiResults).then(function () { Object.keys('apiResults').forEach(function(item, index){ console.log(apiResults[item].responseText) }) });

Here Object.keys will return an array of all the keys in an object.

karan3112
  • 1,867
  • 14
  • 20
  • That still returns undefined for apiResults[key].responseText – Mike Feb 26 '18 at 10:51
  • @mike can you please create a fiddle of your code. As per my understanding the above code should work. – karan3112 Feb 26 '18 at 10:58
  • How do I mimic the AJAX response in jsfiddle? – Mike Feb 26 '18 at 11:00
  • Save the response in a JS variable and run the loop. – karan3112 Feb 26 '18 at 11:02
  • I am going to undo the downvote and mark as the answer - it was because my promise was not waiting for the API success to complete before populating the array. So when I looped through the values, it was empty (and therefore undefined) – Mike Feb 26 '18 at 15:01