var AppPatientsList = JSON.parse(JSON RESPONSE);
var AppPatientsListSort = AppPatientsList.sort(function(a,b){
return a.firstName.toLowerCase() <b.firstName.toLowerCase()
? -1
: a.firstName.toLowerCase()>b.firstName.toLowerCase()
? 1 : 0;
});
var DataArray = [];
for (var i = 0; i < AppPatientsListSort.length; ++i) {
if (AppPatientsListSort[i].firstName === search.value) {
var appointment = {};
appointment.PatientID = AppPatientsListSort[i].PatientID;
appointment.ScheduleDate = AppPatientsListSort[i].ScheduleDate;
alert(appointment.ScheduleDate); // Works fine, i get the date...
}
DataArray[i] = appointment;
}
var RowIndex = 0;
var ScheduleDate = "";
for (i = 0, len = DataArray.length; i < len; i++) {
// Throws me error in this place... WHY?
if (ScheduleDate != DataArray[i].ScheduleDate) {
ScheduleDate = DataArray[i].ScheduleDate;
}
}
What’s wrong with this code, why i am not able to access the ScheduleDate?
You are only initializing the
appointmentvariable when you are inside theifclause, but you are adding it to the array on every iteration.If the first element of
AppPatientsListSortdoes not have the value you search for,DataArray[0]will containundefined.In the second loop you then try to access
DataArray[0].ScheduleDatewhich will throw an error.Update:
Even more important, as JavaScript has no block scope, it might be that several entries in
DataArraypoint to the sameappointmentobject.Depending on what you want to do, everything it takes might be to change
to
and move this statement inside the
ifclause so that only appointments are added that match the search criteria.Further notes: To have a look what your
DataArraycontains, make aconsole.dir(DataArray)before the second loop and inspect the content (assuming you are using Chrome or Safari, use Firebug for Firefox).