Skip to content

Instantly share code, notes, and snippets.

@schester44
Last active October 16, 2018 15:44
Show Gist options
  • Save schester44/a0c2b648650487e3d60168066cc42be1 to your computer and use it in GitHub Desktop.
Save schester44/a0c2b648650487e3d60168066cc42be1 to your computer and use it in GitHub Desktop.
deep flatten nested object
const flatten = (obj, prefix = '') => {
return Object.keys(obj).reduce((acc, key) => {
const value = obj[key]
const prefixedKey = `${prefix}${prefix !== '' ? '.' : ''}${key}`
if (typeof value === "string") {
return {
...acc,
prefixedKey]: curr
};
}
if (value && value.constructor.name.toLowerCase() === "object") {
return {
...acc,
...flatten(value, prefixedKey)
}
}
return acc
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment