Skip to content

Instantly share code, notes, and snippets.

@meltingice
Created February 28, 2013 03:04
Show Gist options
  • Save meltingice/5053848 to your computer and use it in GitHub Desktop.
Save meltingice/5053848 to your computer and use it in GitHub Desktop.
Function to check the existence of a deeply nested object property
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;
}
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