Skip to content

Instantly share code, notes, and snippets.

@john4
Created November 21, 2016 23:37
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 john4/1845ec068a8ac29e2d80bc065921ba6f to your computer and use it in GitHub Desktop.
Save john4/1845ec068a8ac29e2d80bc065921ba6f to your computer and use it in GitHub Desktop.
ES6 flatten object function
// {
// foo: {
// bar: "0",
// baz: {
// hello: "world"
// }
// }
// }
// ...becomes...
// {
// foo/bar: "0",
// foo/baz/hello: "world"
// }
function flattenObject (obj) {
let result = {}
for (let key of Object.keys(obj)) {
let val = obj[key]
// recur
if (typeof val == 'object' && val !== null && val.constructor == Object) {
let flattened = flattenObject(val)
for (let flatKey of Object.keys(flattened)) {
result[key + '/' + flatKey] = flattened[flatKey]
}
}
// base
else {
result[key] = val
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment