Last active
June 9, 2021 19:31
-
-
Save DorinMol/85b5a8629daaea00b2892ac656e87acf to your computer and use it in GitHub Desktop.
Flat nested objects by property [helper function]
This file contains 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
// Helper to extract paths ( root.with.deeply.nested.structure ) and their value using the specified leaf | |
// --- Found a version on the internet and modified it for this purpose. | |
// Using typescript | |
const flattenNestedObjectsByProperty = (object, property: string): { [prop: string]: any } => { | |
const pathsWithValue = {}; | |
const separator: string = '.'; | |
Object.assign({}, ...function _flatten(child, path = ([] as string[])) { | |
return ([] as string[]).concat(...Object.keys(child).map(key => typeof child[key] === 'object' | |
? _flatten(child[key], path.concat([key])) | |
: (key === property && (pathsWithValue[path.join(separator)] = child[key])) | |
)); | |
}(object)); | |
return pathsWithValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment