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

mysql - FireDac error 314 - but DLLs are in program directory -

git - How to list all releases of public repository with GitHub API V3 -

c++ - Getting C2512 "no default constructor" for `ClassA` error on the first parentheses of constructor for `ClassB`? -