Last active
March 22, 2018 20:09
-
-
Save stefanmaric/60fa6d18a42fa24bc4ba84216b04d44d to your computer and use it in GitHub Desktop.
Flatten object function in plain ES5 javascript and ES2015
This file contains hidden or 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
'use strict' | |
function flatten (source, dest, separator, path) { | |
dest = typeof dest !== 'undefined' ? dest : {} | |
separator = typeof separator !== 'undefined' ? separator : '-' | |
path = typeof path !== 'undefined' ? path : [] | |
for (var key in source) { | |
if (!source.hasOwnProperty(key)) continue | |
if (source[key] && typeof source[key] === 'object') { | |
flatten(source[key], dest, separator, path.concat(key)) | |
} else { | |
dest[path.concat(key).join(separator)] = source[key] | |
} | |
} | |
return dest | |
} |
This file contains hidden or 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 flattenObject = (source, separator = '-', path = []) => | |
Object.keys(source).reduce( | |
(acc, key) => | |
Object.assign( | |
{}, | |
acc, | |
source[key] === Object(source[key]) | |
? flattenObject(source[key], separator, path.concat(key)) | |
: { [path.concat(key).join(separator)]: source[key] } | |
), | |
{} | |
) | |
export default flattenObject |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment