frontend-challenges
frontend-challenges copied to clipboard
446 - Get - typescript
index.ts
/**
* Retrieves a value from an object via a path.
*/
export function get<T, R = unknown>(
object: T,
path: string | Array<string | number>,
defaultValue?: R,
): R | unknown {
const keys = Array.isArray(path)
? path
: path.replaceAll("[", ".").replaceAll("]", "").split(".");
let result: any = object[keys[0] as keyof T];
for (let i = 1; i < keys.length; i++) {
const key = keys[i];
result = result[key];
if (result === undefined) return defaultValue;
}
return result;
}