Skip to content

Instantly share code, notes, and snippets.

@jaz303
Created May 6, 2010 08:25
Show Gist options
  • Save jaz303/391921 to your computer and use it in GitHub Desktop.
Save jaz303/391921 to your computer and use it in GitHub Desktop.
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]);
}
}
<script type='text/javascript'>
var obj = {
'foo': {
'bar': {
'getBaz': function() { return 100; }
}
}
};
alert(valueForKey(obj, 'foo.bar.baz'))
// => 100
</script>
@jaz303
Copy link
Author

jaz303 commented May 6, 2010

Allows a JS object to be queried by path, supporting either object properties or getter functions. Similar to Key-Value coding in Cocoa.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment