Created
May 6, 2010 08:25
-
-
Save jaz303/391921 to your computer and use it in GitHub Desktop.
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 valueForKeyRecurse(object, chunks) { | |
var bit = chunks.shift(), val; | |
if (bit in object) { | |
return chunks.length | |
? valueForKeyRecurse(object[bit], chunks) | |
: object[bit]; | |
} else { | |
var getter = object['get' + bit.charAt(0).toUpperCase() + bit.substring(1)]; | |
if (typeof getter == 'function') { | |
return chunks.length | |
? valueForKeyRecurse(getter.call(object), chunks) | |
: getter.call(object); | |
} | |
} | |
return null; | |
} | |
function valueForKey(object, key) { | |
if (key.indexOf('.') > 0) { | |
return valueForKeyRecurse(object, key.split('.')); | |
} else { | |
return valueForKeyRecurse(object, [key]); | |
} | |
} |
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
<script type='text/javascript'> | |
var obj = { | |
'foo': { | |
'bar': { | |
'getBaz': function() { return 100; } | |
} | |
} | |
}; | |
alert(valueForKey(obj, 'foo.bar.baz')) | |
// => 100 | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Allows a JS object to be queried by path, supporting either object properties or getter functions. Similar to Key-Value coding in Cocoa.