I am having some problems with two objects in my javascript code.
My first object is from an API call which I haven't listed here, but the data
variable being passed into my getStudentStats()
function is the result of that API call and its output can be seen in the image below highlighted [1]. It is a list of students and their associated data.
My second object is the result of a JSON call which can be seen below (the UWA.Data.getJson()
function). Its output can be seen in the image below highlighted [2]. It is a list of students' IDs and some statistics from my local database, i.e. the number of flags they've received and the number of interventions that have been raised for them.
getStudentStats : function(data) {
/* [1] Console log */
console.log(data);
var student_list = '';
for( var i = 0; i < data.length; i++ )
student_list += data[i].id + ',';
student_list = student_list.substring(0, student_list.length - 1);
var Students = [];
var Student_Data = data;
UWA.Data.getJson(FLAGS_Assign_Flags.url + 'get_students_stats&arg=' + student_list, function(data) {
/* [2] Console log */
console.log(data);
for( var i = 0; i < data.length; i++ ) {
var Student_ID = data[i].Student_ID;
var obj = { 'flags': data[i].Flags, 'interventions': data[i].Interventions };
Students[Student_ID] = obj;
}
/* [3] Console log */
console.log(Students);
FLAGS_Assign_Flags.displayStudents(Students, Student_Data);
});
},
What I'm trying to do is, basically, display some information from both of these objects (using jQuery .html()
and a string variable).
displayStudents : function(students, data) {
/* Set up our HTML variable which we'll .html() when it's populated */
var StudentsHTML = '<ul id="students_display">';
for( var i = 0; i < data.length; i++ ) {
/* For each student in the `data` object, grab their ID to access the correct element in the students object */
var id = data[i].id;
/* Set up a variable which we'll use to display the students' stats in our LI */
var stats = '<div>';
/* If the student doesn't have any flags or interventions, manually set the text */
if( typeof students[id] != 'undefined' )
stats += ' (F:<span class="f">' + students[id].Flags + '</span>|I:<span class="i">' + students[id].Flags + '</span>)';
else
stats += ' (F:<span class="f">0</span>|I:<span class="i">0</span>)';
stats += '</div>';
/* Produce checkbox, name and stats for each student and add them to the HTML variable */
StudentsHTML += '<li><input type="checkbox" name="students" value="' + data[i].id + '" /> ' + data[i].firstname + ' ' + data[i].surname + stats + '</li>';
}
StudentsHTML += '</ul>';
/* Set the HTML... */
$('#students').html(StudentsHTML);
/* Do some other stuff not relevant to this question! */
FLAGS_Assign_Flags.displayForm();
},
The problem is, as you can see in the image below highlighted [3], my Students
object appears as a load of garbage in console and I can't access any information from it.
Is this a scope issue, or am I setting up my array of objects incorrectly?