Skip to content

Instantly share code, notes, and snippets.

@hara-y-u
Created July 25, 2010 14:58
Show Gist options
  • Save hara-y-u/489612 to your computer and use it in GitHub Desktop.
Save hara-y-u/489612 to your computer and use it in GitHub Desktop.
// access nested hash data using string
// Usage:
// var hash = {"foo": {"bar": true, "baz": false }};
// getVal(hash, "foo.bar".split(".")); //=> true
// getVal(hash, "foo.baz".split(".")); //=> false
// setVal(hash, "foo.baz".split("."), "hoge"); //=> "hoge"
// you can also create new keys step by step (same as accessing with array-style)
function getVal(hash, keys) {
var frst=keys.splice(0,1);
if(keys.length) {
return getVal(hash[frst], keys);
} else {
return hash[frst];
}
}
function setVal(hash, keys, value) {
var frst=keys.splice(0,1);
if(keys.length) {
return setVal(hash[frst], keys, value);
} else {
return hash[frst] = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment