Skip to content

Instantly share code, notes, and snippets.

@alanshaw
Created July 12, 2012 09:54
Show Gist options
  • Save alanshaw/3097092 to your computer and use it in GitHub Desktop.
Save alanshaw/3097092 to your computer and use it in GitHub Desktop.
JavaScript function for checking if an object key chain exists
/**
* <code>
* var o = {
* foo: {
* bar: {
* baz: 'w00t!'
* }
* }
* }
* keyChainExists('foo.bar.baz', o); // -> true
* keyChainExists('foo.bar.boz', o); // -> false
* </code>
*/
function keyChainExists(chain, obj) {
var keys = chain.split('.');
if(obj && obj[keys[0]]) {
if(keys.length > 1) {
return keyChainExists(keys.slice(1).join('.'), obj[keys[0]]);
} else {
return true;
}
} else {
return false;
}
}
// Needs more work:
// <code>keyChainExists('foo', {foo: false}); // -> false</code>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment