Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't render null from JavaScript object's value

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.

like image 813
Ruslan Avatar asked Jul 09 '12 10:07

Ruslan


People also ask

How do you remove null values from an object?

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.

Why null is object in JavaScript?

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.

How do you handle a null value in JavaScript?

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.

Does null === null JavaScript?

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).


1 Answers

$.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.

like image 180
Esailija Avatar answered Sep 28 '22 12:09

Esailija