Skip to content

Instantly share code, notes, and snippets.

@guillim
Last active March 23, 2020 18:49
Show Gist options
  • Save guillim/f525e3e38bd8817881229ca6eae81906 to your computer and use it in GitHub Desktop.
Save guillim/f525e3e38bd8817881229ca6eae81906 to your computer and use it in GitHub Desktop.
flattenObject.js | A simple function to flatten a javascript object #js
//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