Skip to content

Instantly share code, notes, and snippets.

@sorensen
Created April 23, 2014 16:33
Show Gist options
  • Save sorensen/11222536 to your computer and use it in GitHub Desktop.
Save sorensen/11222536 to your computer and use it in GitHub Desktop.
Object flatten
/**
* 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