Skip to content

Instantly share code, notes, and snippets.

@nfeldman
Created September 7, 2011 23:37
Show Gist options
  • Save nfeldman/1202166 to your computer and use it in GitHub Desktop.
Save nfeldman/1202166 to your computer and use it in GitHub Desktop.
hydrate a javascript object from a string
// this is a quick function that may be useful to someone aside from myself. 'Hydrate' might not be the best choice
// of words, but it comes close. This takes a '.' delimited string (and optionally an existing object) and builds
// the javascript object it represents. It was originally declared inside a IIFE where U was an unused property and
// therefore guaranteed to be undefined, so I've wrapped it in one here, too.
(function (G, U) {
function hydrateObject (obj, prop) { // obj is optional
var levels, len, ret;
if (prop === U && typeof obj == 'string') {
prop = obj;
obj = {};
}
levels = prop.split('.').reverse();
len = levels.length;
ret = obj;
while (len--)
obj = obj[levels[len]] || (obj[levels[len]] = {});
return ret;
}
// ... other stuff happened here
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment