Skip to content

Instantly share code, notes, and snippets.

@ddol
Created December 7, 2011 05:23
Show Gist options
  • Save ddol/1441570 to your computer and use it in GitHub Desktop.
Save ddol/1441570 to your computer and use it in GitHub Desktop.
Flatten and re-inflate an n-dimensional nested object
mush = function(){
/* Author: David Dolphin (ddol)
*
* Use this however you see fit, for any reason without attribution. If it works for you, great!
*
* I wrote this so I could (un)pack settings from fancy-settings[1] for settings that contained nested objects.
* This is necessary because Chrome's localStorage is a simple key, value store and does not support nesting.
* To be used in conjunction with .toObject() and .fromObject()
*
* [1] https://github.com/frankkohlhepp/fancy-settings
*/
this.raze = function(obj){
// Takes an n-dimensional nested object and flattens it into a non nested object
// I know the evals here are nasty, if you have a better solution, please get in touch (@ddol on twitter).
var flat = {};
var addObjects = function(parentKey, subObject){
for(var key in subObject){
fullKey = (Boolean(parentKey) ? parentKey + '.' + key : key);
if(isObjectNotList(subObject[key])){
addObjects(fullKey, subObject[key]);
} else {
flat[fullKey] = subObject[key];
}
}
}
var isObjectNotList = function(testObject){
return((testObject instanceof Object) &&
!(testObject instanceof Array));
}
addObjects('', obj);
return flat;
}
this.raise = function(obj){
// Takes an object flattened with raze and re-creates the original object.
var inflated = {};
var counteractToString = function(test){
if(typeof(test) == "string"){
return String('"' + test + '"');
} else if(test instanceof Array){
return String('[' + test + ']');
} else {
return test;
}
}
for(var key in obj){
var splitKey = key.split('.');
for (i=0;i<splitKey.length;i++){
partialKey = splitKey.slice(0,i+1).join("']['");
var undefinedCheck=0;
eval("undefinedCheck = inflated['" + partialKey + "']");
if(undefinedCheck === undefined){
eval("inflated['" + partialKey + "'] = Object()");
}
}
var exeString ="inflated['" + key.replace(/\./g, "']['") + "'] = " + JSON.stringify(obj[key]);
eval(exeString);
}
return inflated;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment