Skip to content

Instantly share code, notes, and snippets.

@stefanmaric
Last active March 22, 2018 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanmaric/60fa6d18a42fa24bc4ba84216b04d44d to your computer and use it in GitHub Desktop.
Save stefanmaric/60fa6d18a42fa24bc4ba84216b04d44d to your computer and use it in GitHub Desktop.
Flatten object function in plain ES5 javascript and ES2015
'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
}
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