Created
April 10, 2019 09:28
-
-
Save mbecker/bbf02f0495ead0bc418096e439cfdf14 to your computer and use it in GitHub Desktop.
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
// 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