Friday, January 18, 2013

[UnderscoreJS] - check for Null values inside a JSON object

Let say you have a JSON object:

var my_object = {
  'name' : 'Catherine',
  'email' : '',
  'city' : 'Vancouver',
  'age' : null,
  'school' : 'Simon Fraser'

To look for any null values might be a bit of work, since we will have to get the list of attributes, and loop through them.

With UnderscoreJS, we are able to validate the object easily.

_.contains(_.values(my_object), null)

_.value(my_object) will return a list of values in your object, in this case it returs:

['Catherine', '', 'Vancouver', null, 'Simon Fraser']

_.contains(list, value) returns true if the list contains the value or else return false.

For more: