Created
April 28, 2020 19:48
-
-
Save atomize/f9210750c81c2736db3d4d5601781ce7 to your computer and use it in GitHub Desktop.
Flatten an object in ES6
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 = object => { | |
return Object.assign({}, ...function _flatten(objectBit, path = '') { //spread the result into our return object | |
return [].concat( //concat everything into one level | |
...Object.keys(objectBit).map( //iterate over object | |
key => typeof objectBit[key] === 'object' ? //check if there is a nested object | |
_flatten(objectBit[key], `${ path }.${ key }`) : //call itself if there is | |
({ | |
[`${ path }.${ key }`]: objectBit[key] | |
}) //append object with it’s path as key | |
) | |
) | |
}(object)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment