Skip to content

Instantly share code, notes, and snippets.

@RichardDillman
Last active April 20, 2023 20:07
Show Gist options
  • Save RichardDillman/a215c690259225528302cb72cc22fa0c to your computer and use it in GitHub Desktop.
Save RichardDillman/a215c690259225528302cb72cc22fa0c to your computer and use it in GitHub Desktop.
Gets the value deep within a path of object. If at any point in the path the key does not exist. We return undefined. If we have a default value and the path does not exist return that default value.
/**
* Gets the value deep within a path of object.
* If at any point in the path the key does not exist. We return undefined.
* If we have a default value and the path does not exist return that default value.
*
* This allows you to avoid constantly checking for properties along the way like
* `this.state.wave && this.state.wave.data && this.state.wave.data.companyName`
*
* @example get(this, "state.wave.data.companyName") // can return undefined
* @example get(this, "state.companyOptions", []); // always returns an array.
*
* @param {Object} target - An object with deep children.
* @param {String} path - A dot delimited string representation of the path to follow.
* @param {*} defaultValue - A return value for when nthe path does not exist.
* @returns {*} Either the value at the end of the path, the default vlaue, or undefined.
*/
export function get(target, path, defaultValue) {
const result = path
.split(".")
.reduce((obj, key) => (obj || {})[key], target);
return result === undefined ? defaultValue : result;
}
/**
* Gets the value deep within a path of object.
* If at any point in the path the key does not exist. We return undefined.
* If we have a default value and the path does not exist return that default value.
*
* This allows you to avoid constantly checking for properties along the way like
* `this.state.wave && this.state.wave.data && this.state.wave.data.companyName`
*
* @example get(this, "state.wave.data.companyName") // can return undefined
* @example get(this, "state.companyOptions", []); // always returns an array.
*/
export function get(target: Record<string,any>, path: string, defaultValue?: any): any {
const result = path
.split(".")
.reduce((obj: Record<string,any>, key: string) => (obj || {})[key], target);
return result === undefined ? defaultValue : result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment