I'm looking for 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 ternary (? :
) operator).
Code sample as follows:
$.each(data, function(index, item) {
return $("div#SearchResults").append(item.PhoneNumber);
}
when item.PhoneNumber is null
, the page renders with a string "null" inside the SearchResults div
, instead I wanted to be empty.
To remove all null values from an object: Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array of keys. Check if each value is equal to null and delete the null values using the delete operator.
In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. You can consider it a bug in JavaScript that typeof null is an object.
JavaScript uses the null value to represent a missing object. Use the strict equality operator ( === ) to check if a value is null . The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.
Summary. null is a special value in JavaScript that represents a missing object. The strict equality operator determines whether a variable is null: variable === null . typoef operator is useful to determine the type of a variable (number, string, boolean).
$.each(data, function(index, item) {
return $("div#SearchResults").append(item.PhoneNumber || "");
}
With $.trim
(unexpectedly converts null
and undefined
to empty string):
$.each(data, function(index, item) {
return $("div#SearchResults").append($.trim(item.PhoneNumber));
}
Unexpected because it's both unintuitive and undocumented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With