Skip to content

Instantly share code, notes, and snippets.

@mbecker
Created April 10, 2019 09:28
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 mbecker/bbf02f0495ead0bc418096e439cfdf14 to your computer and use it in GitHub Desktop.
Save mbecker/bbf02f0495ead0bc418096e439cfdf14 to your computer and use it in GitHub Desktop.
// https://jsfiddle.net/L1pozdj6/
// Source: https://stackoverflow.com/questions/33036487/one-liner-to-flatten-nested-object - Webber
/**
* Flatten a multidimensional object
*
* For example:
* {
* "a": 1,
* "b": {
* "c": 2,
* "d": {
* "e": {
* "f": 3
* }
* }
* }
*}
* Returns:
* {
* "a": 1,
* "b-c": 2,
* "b-d-e-f": 3
* }
*/
const flattenObject = (obj, keyold = "") => {
const flattened = {}
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === 'object') {
Object.assign(flattened, flattenObject(obj[key], keyold + key + "-"))
} else {
flattened[keyold + key] = obj[key]
}
})
return flattened
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment