I have an unusual problem and I can't determine why it's happening. I've created an object, and I update the values from within a loop. After this loop completes, I attempt to access a value which is undefined. I think this is simply best demonstrated by showing you my code. Can anyone help me to understand what's happening here?
function loadCounts() {
var counts = {
enroll: {},
term: {},
change: {}
};
var forms = [
"enroll/pending",
"enroll/approved",
"term/pending",
"term/approved",
"change/pending",
"change/approved",
];
$.each(forms, function( index, value ) {
if (!(value.split("/")[0] in counts)) {
counts[value.split("/")[0]] = {};
}
$.ajax({
url: apiURL+'/online/payroll/admin/dashboard/counts/'+value,
headers: { 'Authorization': 'Bearer ' + sessionStorage.getItem('apiToken') },
crossDomain: true,
method: 'GET',
dataType: 'json',
success: function(response) {
counts[value.split("/")[0]][value.split("/")[1]] = response.count;
},
error: function (XMLHttpRequest) {
console.log("error", XMLHttpRequest)
}
});
});
console.log('count object:', counts)
console.log('enroll object:', counts.enroll)
console.log('pending count:', counts.enroll.pending)
}
loadCounts();
And the result in console: