Created
July 12, 2012 09:54
-
-
Save alanshaw/3097092 to your computer and use it in GitHub Desktop.
JavaScript function for checking if an object key chain exists
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
/** | |
* <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