简体   繁体   中英

Shortcut to check if JSON objects are null

I'm writing a code to parse a JSON file. I was wondering if there is a shortcut to check if any of the objects is null and return "No Information" to each of them so that I don't have to repeat '+(item.xxx || 'No Information')+' . Is there such a shortcut?

For example, I'm doing this to check if the object is null:

$(data.items).each(function (index, item) { 
    item_html +='<h3>'+item.title+'</h3><p>'+(item.description || 'No Information')+'<p>'+(item.date || 'No Information')+'<p>'+(item.source || 'No Information')+'<p>'+(item.month|| 'No Information')+';
}

Is there any better alternative?

jQuery has a jQuery.isEmptyObject function.

$(data.items).each(function (index, item) { 
    if (!jQuery.isEmptyObject(item)) {
        item_html +='<h3>'+item.title+'</h3<p>'+item.description+'<p>'+item.date+'<p>'+item.source+'<p>'+item.month+';
    }
}

It's still not the worst idea to check each property to see if it's undefined. Try taking the logic out of the html building, like var itemDate = item.date || "No Information"; var itemDate = item.date || "No Information";

You also have some HTML and Javascript syntax errors. Close your <p> tags, and close your string at the end of the line.

write a simple function

function s(item){
    if (item==null){
        return "No Inofrmation";
    }else{
        return item;
    }
 }

USAGE

$(data.items).each(function (index, item) { 
item_html +='<h3>'+item.title+'</h3><p>'+s(item.description)+'<p>'+s(item.date)+'<p>'+s(item.source)+'<p>'+s(item.month)'</p>';
}

This could be a first version:

var na = function(message, def){
  def || (def = 'No Information');
  return message || def;
};

$(data.items).each(function (index, item) { 
   item_html +='<h3>'+item.title+'</h3><p>'+
     na(item.description)+'<p>'+
     na(item.date)+'<p>'+
     na(item.source)+'<p>'+
     na(item.month)+'<p>'
}

Although it would be better if you do this logic in your data source, from where you get data.items ?

you can also use the map command to preprocess your array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

var fields = ['title', 'field1', 'flield2'];
items.map(function(item){
    for(var f in fields){
        fn = fields[f];
        if(item[fn] == undefined || item[fn] == null){
            item[fn] = 'No Information';
        }
    }
});

This is sort of a "hack" but you could print as is then replace all ocurrences of undefined:

$(data.items).each(function (index, item) { 
    item_html +='<h3>'+item.title+'</h3><p>'+item.description+'<p>'+item.date+'<p>'+item.source+'<p>'+item.month;
}

item_html.split(">undefined<").join(">No Information<");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM