Skip to content

Instantly share code, notes, and snippets.

@ailequal
Last active July 13, 2023 10:01
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 ailequal/293431a726895326458ccefc01f1e52b to your computer and use it in GitHub Desktop.
Save ailequal/293431a726895326458ccefc01f1e52b to your computer and use it in GitHub Desktop.
getValueFromPath
/**
* Retrive the specific value from an object, given the property path separated by a splitter.
* The generic defines the expected return type.
* Beware that, for example, defining a generic "string" won't assure us
* that the value from the object will have the same type. We are "trusting" the object.
*
* @param object
* @param path
* @param splitter
*/
export default <T>(
object: Record<string, unknown>,
path: string,
splitter = '.'
): T | undefined => {
if (!path) return undefined;
const keys = path.split(splitter);
let value: unknown = object;
try {
for (const key of keys) {
if (!key || !(value instanceof Object) || !(key in value)) return undefined;
value = (value as Record<string, unknown>)[key];
}
return value as T;
} catch (err) {
return undefined;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment