Skip to content

Instantly share code, notes, and snippets.

@wmbenedetto
Last active December 14, 2015 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmbenedetto/5080102 to your computer and use it in GitHub Desktop.
Save wmbenedetto/5080102 to your computer and use it in GitHub Desktop.
Converts a multi-dimensional object to single-dimensional object in JavaScript. Dot-notated paths are used as object keys to represent nesting depth and to facilitate re-inflation.
/* Adding deflate() to the Object prototype */
Object.prototype.deflate = function(pathArray,result){
pathArray = (typeof pathArray === 'undefined') ? [] : pathArray;
result = (typeof result === 'undefined') ? {} : result;
var key, value, newKey;
for (var i in this){
if (this.hasOwnProperty(i)){
key = i;
value = this[i];
pathArray.push(key);
if (typeof value === 'object' && value !== null){
result = value.deflate(pathArray,result);
} else {
newKey = pathArray.join('.');
result[newKey] = value;
}
pathArray.pop();
}
}
return result;
};
/* Creating deflate() as a standalone function */
var deflate = function(source,pathArray,result){
pathArray = (typeof pathArray === 'undefined') ? [] : pathArray;
result = (typeof result === 'undefined') ? {} : result;
var key, value, newKey;
for (var i in source){
if (source.hasOwnProperty(i)){
key = i;
value = source[i];
pathArray.push(key);
if (typeof value === 'object' && value !== null){
result = deflate(value,pathArray,result);
} else {
newKey = pathArray.join('.');
result[newKey] = value;
}
pathArray.pop();
}
}
return result;
};
/*----------- Usage examples -----------*/
var obj = {
foo : {
bar : {
baz : 'SUCCESS!',
biz : ['first','second','third']
}
}
};
/* Using the Object prototype version */
obj.deflate();
// RETURNS:
// {
// "foo.bar.baz": "SUCCESS!",
// "foo.bar.biz.0": "first",
// "foo.bar.biz.1": "second",
// "foo.bar.biz.2": "third"
// }
/* Using the standalone function version */
deflate(obj);
// RETURNS:
// {
// "foo.bar.baz": "SUCCESS!",
// "foo.bar.biz.0": "first",
// "foo.bar.biz.1": "second",
// "foo.bar.biz.2": "third"
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment