Skip to content

Instantly share code, notes, and snippets.

@atomize
Created April 28, 2020 19:48
Show Gist options
  • Save atomize/f9210750c81c2736db3d4d5601781ce7 to your computer and use it in GitHub Desktop.
Save atomize/f9210750c81c2736db3d4d5601781ce7 to your computer and use it in GitHub Desktop.
Flatten an object in ES6
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