Skip to content

Instantly share code, notes, and snippets.

@employee451
Created May 30, 2022 11:55
Show Gist options
  • Save employee451/b4414c0cc4f5a818eea82f881c4dc227 to your computer and use it in GitHub Desktop.
Save employee451/b4414c0cc4f5a818eea82f881c4dc227 to your computer and use it in GitHub Desktop.
/**
* 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