Dealing with missing property/keys in AJAX GET JSON request -


sometimes json object called ajax request missing key/property of value want display in table. problem when key missing causes "typeerror: cannot read property 'name' of undefined" logged in console , breaks code. tried using || statement didn't work. see code snippet below:

function getnextobject() {   $.ajax({     url: "http://scrapi.org/object/" + randomnum,     success: function(data) {       var timeline = data.timelinelist[0].name || "not available";       var medium = data.medium;       var culture = data.culture;       var geo = data.geography;       var date = data.datetext;       var gallery = data.gallerylink;       var title = data.title;       var artist = data.primaryartist.name || "not available";       var image = data.currentimage.imageurl; 

primaryartist , timelinelist not contained in json object throwing error , causing code break. how can overcome this?

the problem code trying .name of these variables , variables empty.

you build if around variables timelinelist , primaryartist

how try these replacements:

var timeline = data.timelinelist ? data.timelinelist[0].name : "not available"; ... var artist = data.primaryartist ? data.primaryartist.name : "not available"; 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -