Last active
March 23, 2020 18:49
-
-
Save guillim/f525e3e38bd8817881229ca6eae81906 to your computer and use it in GitHub Desktop.
flattenObject.js | A simple function to flatten a javascript object #js
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
//A simple function to flatten a javascript object, with a '.' delimiter between nested levels | |
const flatten = (objectOrArray, prefix = '', formatter = (k) => (k)) => { | |
const nestedFormatter = (k) => ('.' + k) | |
const nestElement = (prev, value, key) => ( | |
(value && typeof value === 'object') | |
? { ...prev, ...flatten(value, `${prefix}${formatter(key)}`, nestedFormatter) } | |
: { ...prev, ...{ [`${prefix}${formatter(key)}`]: value } }); | |
return Array.isArray(objectOrArray) | |
? objectOrArray.reduce(nestElement, {}) | |
: Object.keys(objectOrArray).reduce( | |
(prev, element) => nestElement(prev, objectOrArray[element], element), | |
{}, | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment