Created
May 30, 2022 11:55
-
-
Save employee451/b4414c0cc4f5a818eea82f881c4dc227 to your computer and use it in GitHub Desktop.
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
/** | |
* Safely gets a value from object using the provided path. Return `undefined` if it doesn't exist | |
* Similar to lodash.get: https://lodash.com/docs/#get | |
* | |
* @param {{}} obj - target object | |
* @param {string} path - path to a nested value | |
* @param {*} defaultValue - gets returned if path resolved to `undefined` | |
* | |
* @see https://gist.github.com/jeneg/9767afdcca45601ea44930ea03e0febf#gistcomment-1935901 | |
*/ | |
const getNestedProperty = ( | |
obj: Record<string, any>, | |
path: string, | |
defaultValue?: unknown | |
): any => | |
path | |
.replace(/\[(\d+)]/g, '.$1') | |
.split('.') | |
.filter(Boolean) | |
.every((step: string | number) => (obj = obj[step]) !== undefined) | |
? obj | |
: defaultValue | |
export default getNestedProperty |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment