Do not show null value from JavaScript object value

I am looking for the most efficient way to output empty string instead of "null" for null values. Is there a way to do this without conditional statements (i.e. if or triple ( ? : ).

Sample code as follows:

 $.each(data, function(index, item) { return $("div#SearchResults").append(item.PhoneNumber); } 

when item.PhoneNumber is null , the page is displayed with the string null "inside the SearchResults div , instead I would like to be blank .

+8
javascript jquery html
source share
4 answers
 $.each(data, function(index, item) { return $("div#SearchResults").append(item.PhoneNumber || ""); } 

With $.trim (unexpectedly converts null and undefined to an empty string):

 $.each(data, function(index, item) { return $("div#SearchResults").append($.trim(item.PhoneNumber)); } 

Unexpectedly, because it is unintuitive and undocumented.

+17
source share

If you really decide not to use if or triple to evaluate the variable, then you can use the || :

 $.each(data, function(index, item) { return $("div#SearchResults").append(item.PhoneNumber || ''); } 

But to be honest, just use a conditional statement for what they are intended, and helps to provide a certain degree of security in your execution and output of the script.

+7
source share

Try it,

 $.each(data, function(index, item) { return $("div#SearchResults").append(item.PhoneNumber?item.PhoneNumber:""); } 
+1
source share

Without jQuery:

 $.each(data, function(index, item) { return $("div#SearchResults").append([item.PhoneNumber].join('')); } 
0
source share

All Articles