Skip to content

Instantly share code, notes, and snippets.

@guybrush
Created August 16, 2010 03:55
Show Gist options
  • Save guybrush/526372 to your computer and use it in GitHub Desktop.
Save guybrush/526372 to your computer and use it in GitHub Desktop.
stringObj
(function(exports, undefined) {
/**
* create/access objects with a key-string
*
* with eval(): with stringObj():
* ----------------------------- ------------------------------
* var keyString = 'json.data' var keyString = 'json.data'
* , value = 'a value'; , value = 'a value';
* eval(keyString+' = '+value); stringObj(keyString, value);
* alert(eval(keyString)); alert(stringObj(keyString));
*
* @param String keyString (ie. `a.b.c.d`)
* @param Mixed value
* @return Mixed value of selected key, or if 2 parameters are passed
* the resulting object will be returned
*/
var stringObj = exports.stringObj = function(keyString, value) {
var keys = keyString.split('.'),
data = exports[keys[0]] = exports[keys[0]] || {},
keys = keys.slice(1);
if (!value) { // get data
var value = data;
for (var i=0, len=keys.length; i<len; i++) {
if (value === undefined) return false;
value = value[keys[i]];
}
return value;
} else { // set data
var temp = data;
for (var i=0, len=keys.length; i<len; i++) {
if (i==(len-1)) {
temp[keys[i]] = value;
} else {
temp[keys[i]] = temp[keys[i]] || {};
temp = temp[keys[i]];
}
}
return data;
}
};
})((function() {
if (typeof exports === 'undefined') {
return window;
} else {
return exports;
}
})());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment