I wrote the below code, and some more, to quickly build a prototype for a 3 screen web application. Not planning to use it for production. The project is almost finished, but there is one issue that is perplexing me. I get an error - Cannot read property 'first_name' of undefined
, even though there is a check first whether the object has the property reported as undefined. Realize the code is not an example of how such things should be handled, but why does it not work? To prevent context funkiness, I even clone the array - probably unnecessary. What causes the undefined error?
$.ajax({
url: '/api/v1/departures/' + routeID + '/',
method: 'GET',
headers: {
'Authorization': 'Token '+ owner_token]
},
contentType:'application/json',
success: function(departures) {
console.log('departures: ' + JSON.stringify(departures));
if ( departures && ( 0 < departures.length)) {
var template = '';
for ( var j = 0; j < departures.length; j++) {
if (departures[j].route == routeID) {
var seats = (departures[j].seats).slice(0);
for ( var i = 0; i < seats.length; i++) {
template += '<div class="right-seat" data-id="' + seats[i].seat + '">' +
'<div class="right-seat-place">SEAT ' + seats[i].seat + '</div>' +
'<div class="right-seat-name">' +
seats[i].hasOwnProperty('passenger') ? seats[i].passenger.first_name + ' ' + seats[i].passenger.last_name : '' +
'</div>' +
'<div class="right-seat-reserved"><i class="glyphicon glyphicon-check"></i> ' +
seats[i].hasOwnProperty('passenger') ? 'Reserved' : 'Available' +
'</div>' +
'</div>';
}
}
}
$('div.right-top-controls').after(template);
}
},
error: function() {
alert('error!');
}
});
Please advise.
Thank you.