Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created November 13, 2011 00:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanflorence/1361373 to your computer and use it in GitHub Desktop.
Save ryanflorence/1361373 to your computer and use it in GitHub Desktop.
See if an object has a property
var has = function (obj, property) {
var tree = obj,
split = property.split('.'),
last = split.pop();
while (next = split.shift()) {
tree = tree[next];
if (tree === undefined) return false;
}
return tree[last] === undefined ? false : true;
};
console.assert( has(o, 'foo'), 'foo');
console.assert( has(o, 'foo.bar'), 'foo.bar' );
console.assert( !has(o, 'bar'), 'bar' );
console.assert( !has(o, 'foo.bar.baz'), 'foo.bar.baz' );
@ryanflorence
Copy link
Author

I have this in an AMD module like:

define('util/obj', function () {
  has: function (obj, property) { /* def */ },
  /* other object utilities */
}

So my usage looks like:

object.has(o, 'foo.bar.baz');

@Joeppie
Copy link

Joeppie commented Dec 19, 2013

I fear that the comparison with undefined after using the [] accessor on an object is not the most correct way to establish whether or not an object has a property. In JavaScript it is possible for someone to assign the value of undefined onto a variable or property.

While technically the object would then have the property, this code would claim it does not.

Consider Resig's answer in this StackOverflow question on the topic:
http://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-a-property-in-javascript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment