JavaScript / HTML / CSS / PHP

20Oct/10Off

Checking object properties

When I'm working with an object and I need to check a property, I cannot go straight up I always first check if this one exists, but we have different ways to check them, before I used to do this.

   if (object.property) {
       //exists
       console.log(object.property);
   }

It works when the property is undefined, but if the property has false ,zero(0), or empty string ("") it wont work as we wanted.

Other way is checking if it has its own property by using

if (object.hasOwnProperty("property")) {
   //exists
   console.log(object.property);
}

But here you are just checking the properties that come with the object, not the ones that are inherited by the prototype chain. So in case you want to check all the properties use this code.

if ("property" in object) {
   //exists
   console.log(object.property);
}

It's really annoying checking long objects structures

   var object = {
  data: {
    item: {
      sub_item: {
        bla: {
          here : {
            iam: true
          }
        }
      }
    }
  }
};  
// This could throw us a Reference Error
if (data.item.sub_item.bla.here.iam) {
  //it works
}
//Other way could be...
if (data)
  if ("item" in data)
     if ("sub_item" in data.item)
       if ("bla" in data.item.sub_item)
          if ("here" in data.item.sub_item.bla) {
             //don't do this
          }

Try this snippet:

Array.prototype.some = function(fn, thisObj) {
  var scope = thisObj || window;
  for ( var i=0, j=this.length; i < j; ++i ) {
    if ( fn.call(scope, this[i], i, this) ) {
      return true;
    }
  }
  return false;
};
function isSet (object, string) {
  if (!object) return false;
  var childs = string.split('.');
  if (childs.length > 0 ) {
    return !childs.some(function (item) {
      if (item in object) {
        object = object[item];
        return false;
      } else return true;
    });
  } else if (string in object) {
    return true;
  } else return false;
}

var object = {
  data: {
    item: {
      sub_item: {
        bla: {
          here : {
            iam: true
          }
        }
      }
    }
  }
};

console.log(isSet(object,'data.item')); // true
console.log(isSet(object,'x')); // false
console.log(isSet(object,'data.item')); // true
console.log(isSet(object,'data.item.sub_item.bla.here.iam')); // true
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • StumbleUpon
  • Twitter
Filed under: javascript Comments Off
Comments (1) Trackbacks (2)

Leave a comment

You must be logged in to post a comment.

Trackbacks are disabled.