lib/func.ts (view raw)
1type Path = string | Array<string | number>;
2
3export const get = <T = string>(
4 object: Record<string, any>,
5 path: Path,
6 defaultValue?: T
7): T => {
8 if (!object || typeof object !== "object") return defaultValue as T;
9
10 const pathArray = Array.isArray(path)
11 ? path
12 : path
13 .split(".")
14 .map(key =>
15 key.includes("[") ? key.replace(/\[(\d+)\]/g, ".$1") : key
16 )
17 .join(".")
18 .split(".");
19
20 let result: any = object;
21 for (let key of pathArray) {
22 result = result?.[key];
23 if (result === undefined) return defaultValue as T;
24 }
25
26 return result;
27};