i wrote below code, , more, build prototype 3 screen web application. not planning use production. project finished, there 1 issue perplexing me. error - cannot read property 'first_name' of undefined
, though there check first whether object has property reported undefined. realize code not example of how such things should handled, why not work? prevent context funkiness, clone array - unnecessary. causes 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 = ''; ( var j = 0; j < departures.length; j++) { if (departures[j].route == routeid) { var seats = (departures[j].seats).slice(0); ( var = 0; < 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.
hasownproperty
checks if object has property name. doesn't check value is. value undefined
.
// doesn't have property , accessing returns undefined var = {}; console.log(a.hasownproperty('prop')); console.log(a.prop); // has property , value not undefined var b = { prop: 1 }; console.log(b.hasownproperty('prop')); console.log(b.prop); // has property , it's value undefined var c = { prop: undefined }; console.log(c.hasownproperty('prop')); console.log(c.prop);
this means seats[i]
may have passenger
property it's value still undefined
.
there's problem you're using ternary operation during string concatenation. essentially, +
has higher precedence ?:
results in concatenation occurring before conditional evaluated. fix this, wrap ternaries in parentheses.
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>';