Created
April 16, 2020 00:10
-
-
Save cvan/00f482311fedbab0c560c8fc1e676e1e to your computer and use it in GitHub Desktop.
flatten a nested JavaScript object to a flatten one-level object
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
// Adapted from source: https://stackoverflow.com/a/19204980 | |
const flatten = (function(isArray, wrapped) { | |
return function(table) { | |
return reduce('', {}, table); | |
}; | |
function reduce(path, accumulator, table) { | |
if (isArray(table)) { | |
const length = table.length; | |
if (length) { | |
let index = 0; | |
while (index < length) { | |
const property = path + '[' + index + ']'; | |
const item = table[index++]; | |
if (wrapped(item) === item) { | |
reduce(property, accumulator, item); | |
} else { | |
accumulator[property] = item; | |
} | |
} | |
} else accumulator[path] = table; | |
} else { | |
let empty = true; | |
let item; | |
let property; | |
if (path) { | |
for (property in table) { | |
item = table[property]; | |
property = path + '.' + property; | |
empty = false; | |
if (wrapped(item) === item) { | |
reduce(property, accumulator, item); | |
} else { | |
accumulator[property] = item; | |
} | |
} | |
} else { | |
for (property in table) { | |
item = table[property]; | |
empty = false; | |
if (wrapped(item) === item) { | |
reduce(property, accumulator, item); | |
} else { | |
accumulator[property] = item; | |
} | |
} | |
} | |
if (empty) { | |
accumulator[path] = table; | |
} | |
} | |
return accumulator; | |
} | |
})(Array.isArray, Object); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment