Last active
December 14, 2015 11:38
-
-
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.
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
/* 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