Last active
June 1, 2020 16:36
-
-
Save connebs/55a3f84c9eadcf34b02bdb05570db5ff to your computer and use it in GitHub Desktop.
Flatten a nested object into a flat object keyed by path strings
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 flatten = (obj, flattened, prevStringKey) => { | |
| Object.entries(obj).forEach(([key, value]) => { | |
| const stringKey = prevStringKey ? `${prevStringKey}.${key}` : key; | |
| if (typeof value === 'object') { | |
| flattened = flatten(value, flattened, stringKey); | |
| } else { | |
| flattened[stringKey] = value; | |
| } | |
| }); | |
| return flattened; | |
| }; | |
| const path = { in: { big: { object: true, another: false } }, out: { final: { countdown: 100 } } }; | |
| console.log(flatten(path, {}, 'path')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment