-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget.ts
71 lines (66 loc) · 1.74 KB
/
get.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Please refer to the terms of the license agreement in the root of the project
*
* (c) 2024 Feedzai
*/
import { isNil } from "..";
/**
* Gets the property value at path of object. If the resolved value is undefined the defaultValue is used
* in its place.
*
* @example
*
* const simpleObject = { a: { b: 2 } }
* const complexObject = { a: [{ bar: { c: 3 } }] }
* const falsyObject = { a: null, b: undefined, c: 0 }
*
* get(simpleObject, 'a.b')
* // => 2
*
* get(complexObject, 'a[0].bar.c')
* // => 3
*
* get(complexObject, ['a', '0', 'bar', 'c'])
* // => 2
*
* get(simpleObject, 'a.bar.c', 'default')
* // => 'default'
*
* get(complexObject, 'a.bar.c', 'default')
* // => 'default'
*
* get(complexObject, null)
* // => undefined
*
* get(falsyObject, 'a', 'default')
* // => null
*
* get(falsyObject, 'b', 'default')
* // => undefined
*
* get(falsyObject, 'c', 'default')
* // => zero
*
* @param object The object to query.
* @param path The path of the property to get.
* @param defaultValue The value returned if the resolved value is undefined.
* @return Returns the resolved value.
*/
export function get<T = unknown, TDefault = T>(
value: any,
path: string | string[],
defaultValue?: TDefault
): T | TDefault | undefined {
if (isNil(path)) {
return undefined;
}
const PATH_SEGMENTS = Array.isArray(path) ? path : path.split(/[\.\[\]]/g);
let CURRENT_VALUE: any = value;
for (const key of PATH_SEGMENTS) {
if (CURRENT_VALUE === null || CURRENT_VALUE === undefined) return defaultValue;
if (key.trim() === "") continue;
CURRENT_VALUE = CURRENT_VALUE[key];
}
return CURRENT_VALUE === undefined ? defaultValue : CURRENT_VALUE;
}