Created
February 28, 2013 03:04
-
-
Save meltingice/5053848 to your computer and use it in GitHub Desktop.
Function to check the existence of a deeply nested object property
This file contains hidden or 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
function hasProperty() { | |
var args = Array.prototype.slice.call(arguments, 0); | |
var obj = args.shift(); | |
var ref = obj; | |
for (var i = 0, _len = args.length; i < _len; i++) { | |
if (!ref[args[i]]) return false; | |
ref = ref[args[i]]; | |
} | |
return true; | |
} |
This file contains hidden or 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 test = { | |
foo: { | |
bar: { | |
abc: true | |
} | |
} | |
}; | |
if (hasProperty(test, 'foo', 'bar', 'abc')) { | |
// this runs | |
} | |
if (hasProperty(test, 'foo', 'baz')) { | |
// this does not run | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment