Created
April 23, 2014 16:33
-
-
Save sorensen/11222536 to your computer and use it in GitHub Desktop.
Object flatten
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
/** | |
* Object flattener | |
* http://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects | |
* | |
* @param {Object} obj to flatten | |
* @return {Object} flattened obj | |
*/ | |
function flatten(data) { | |
var result = {} | |
, isEmpty, prop, i, len | |
function recurse (current, path) { | |
if (Object(current) !== current) { | |
return result[path] = current | |
} | |
if (Array.isArray(current)) { | |
for (i = 0, len = current.length; i < len; i++) { | |
recurse(current[i], path + '[' + i + ']') | |
} | |
if (len == 0) { | |
result[path] = [] | |
} | |
return | |
} | |
isEmpty = true | |
for (prop in current) { | |
isEmpty = false; | |
recurse(current[prop], path ? path + '.' + prop : prop) | |
} | |
if (isEmpty && path) { | |
result[path] = {} | |
} | |
} | |
recurse(data, '') | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment