1 import { isDefined } from "./is-defined"
2
3 export function removeUndefinedProperties<T extends object>(inputObj: T): T {
4 const removeProperties = (obj: T) => {
5 const res = {} as T
6
7 Object.keys(obj).reduce((acc: T, key: string) => {
8 if (typeof obj[key] === "undefined") {
9 return acc
10 }
11 acc[key] = removeUndefinedDeeply(obj[key])
12 return acc
13 }, res)
14
15 return res
16 }
17
18 return removeProperties(inputObj)
19 }
20
21 function removeUndefinedDeeply(input: unknown): any {
22 if (isDefined(input)) {
23 if (input === null || input === "null") {
24 return null
25 } else if (Array.isArray(input)) {
26 return input
27 .map((item) => {
28 return removeUndefinedDeeply(item)
29 })
30 .filter((v) => isDefined(v))
31 } else if (Object.prototype.toString.call(input) === "[object Date]") {
32 return input
33 } else if (typeof input === "object") {
34 return Object.keys(input).reduce(
35 (acc: Record<string, unknown>, key: string) => {
36 if (typeof input[key] === "undefined") {
37 return acc
38 }
39 acc[key] = removeUndefinedDeeply(input[key])
40 return acc
41 },
42 {}
43 )
44 } else {
45 return input
46 }
47 }
48 }