Last active
October 16, 2018 15:44
-
-
Save schester44/a0c2b648650487e3d60168066cc42be1 to your computer and use it in GitHub Desktop.
deep flatten nested 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
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