Skip to content

Instantly share code, notes, and snippets.

@DorinMol
Last active June 9, 2021 19:31
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 DorinMol/85b5a8629daaea00b2892ac656e87acf to your computer and use it in GitHub Desktop.
Save DorinMol/85b5a8629daaea00b2892ac656e87acf to your computer and use it in GitHub Desktop.
Flat nested objects by property [helper function]
// 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