Created
September 7, 2011 23:37
-
-
Save nfeldman/1202166 to your computer and use it in GitHub Desktop.
hydrate a javascript object from a string
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
// 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