Last active
July 13, 2023 10:01
-
-
Save ailequal/293431a726895326458ccefc01f1e52b to your computer and use it in GitHub Desktop.
getValueFromPath
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
/** | |
* 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