-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetValueAtPath.ts
49 lines (45 loc) · 1.06 KB
/
getValueAtPath.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
Given an unknown object and a path, returns the value at the specified path. Returns undefined if the path doesn't lead to a value.
Example:
```ts
const obj = {
name: 'John',
age: 25,
address: {
street: '123 Main St',
city: 'Anytown',
},
};
const name = getValueAtPath(obj, ['name']); // 'John'
const age = getValueAtPath(obj, ['age']); // 25
const street = getValueAtPath(obj, ['address', 'street']); // '123 Main St'
```
*/
export function getValueAtPath<T = unknown>(obj: unknown, path: ReadonlyArray<string | number>): T | undefined
{
let current: unknown = obj;
for (const key of path)
{
if (current === null || current === undefined)
{
return undefined;
}
if (typeof key === 'number')
{
if (!Array.isArray(current))
{
return undefined;
}
current = current[key];
}
else
{
if (typeof current !== 'object' || current === null)
{
return undefined;
}
current = (current as Record<string, unknown>)[key];
}
}
return current as T;
}