|
1
|
type RemapInputObject = Record<string, unknown[]> |
|
2
|
type RemapConfig = { mapTo: string; valueFrom: string } |
|
3
|
export type MapToConfig = { |
|
4
|
[key: string]: RemapConfig[] |
|
5
|
} |
|
6
|
|
|
7
|
/** |
|
8
|
* Create a new object with the keys remapped and the values picked from the original object based |
|
9
|
* on the map config |
|
10
|
* |
|
11
|
* @param object input object |
|
12
|
* @param mapTo configuration to map the output object |
|
13
|
* @param removeIfNotRemapped if true, the keys that are not remapped will be removed from the output object |
|
14
|
* @param pick if provided, only the keys in the array will be picked from the output object |
|
15
|
*/ |
|
16
|
export function mapObjectTo< |
|
17
|
TResult = any, |
|
18
|
T extends RemapInputObject = RemapInputObject |
|
19
|
>( |
|
20
|
object: T, |
|
21
|
mapTo: MapToConfig, |
|
22
|
{ |
|
23
|
removeIfNotRemapped, |
|
24
|
pick, |
|
25
|
}: { removeIfNotRemapped?: boolean; pick?: string[] } = {} |
|
26
|
): TResult { |
|
27
|
removeIfNotRemapped ??= false |
|
28
|
|
|
29
|
const newObject: Record<string, any> = {} |
|
30
|
|
|
31
|
for (const key in object) { |
|
32
|
const remapConfig = mapTo[key as string]! |
|
33
|
|
|
34
|
if (!remapConfig) { |
|
35
|
if (!removeIfNotRemapped) { |
|
36
|
newObject[key] = object[key] |
|
37
|
} |
|
38
|
continue |
|
39
|
} |
|
40
|
|
|
41
|
remapConfig.forEach((config) => { |
|
42
|
if (pick?.length && !pick.includes(config.mapTo)) { |
|
43
|
return |
|
44
|
} |
|
45
|
|
|
46
|
newObject[config.mapTo] = object[key] |
|
47
|
.map((obj: any) => obj[config.valueFrom]) |
|
48
|
.filter(Boolean) |
|
49
|
}) |
|
50
|
} |
|
51
|
|
|
52
|
return newObject as TResult |
|
53
|
} |