1 import { isObject } from "./is-object"
2
3 export function pickDeep<T extends object = object>(
4 input: object,
5 fields: Array<number | string>,
6 prefix: string = ""
7 ): T {
8 if (!input) {
9 return input
10 }
11
12 return Object.entries(input).reduce((nextInput, [key, value]) => {
13 const fieldKey = withPrefix(key, prefix)
14 const fieldMatches = fields.includes(fieldKey)
15 const partialKeyMatch =
16 fields.filter((field) => field.toString().startsWith(`${fieldKey}.`))
17 .length > 0
18
19 const valueIsObject = isObject(value)
20 const valueIsArray = Array.isArray(value)
21
22 if (fieldMatches && (valueIsObject || valueIsArray)) {
23 nextInput[key] = value
24
25 return nextInput
26 }
27
28 if (!fieldMatches && !partialKeyMatch) {
29 return nextInput
30 }
31
32 if (valueIsArray) {
33 nextInput[key] = value.map((arrItem) => {
34 if (isObject(arrItem)) {
35 return pickDeep(arrItem, fields, withPrefix(key, prefix))
36 }
37 return arrItem
38 })
39
40 return nextInput
41 } else if (valueIsObject) {
42 if (Object.keys(value).length) {
43 nextInput[key] = pickDeep(value, fields, withPrefix(key, prefix))
44 }
45
46 return nextInput
47 }
48
49 if (fieldMatches) {
50 nextInput[key] = value
51 }
52
53 return nextInput
54 }, {} as T)
55 }
56
57 function withPrefix(key: string, prefix: string): string {
58 if (prefix.length) {
59 return `${prefix}.${key}`
60 } else {
61 return key
62 }
63 }