Created
November 13, 2011 00:42
-
-
Save ryanflorence/1361373 to your computer and use it in GitHub Desktop.
See if an object has a property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' ); |
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
I have this in an AMD module like:
So my usage looks like: