@@ -6,30 +6,43 @@ function isEmptyObject(obj: unknown) {
6
6
return typeof obj === 'object' && obj !== null && ! Object . keys ( obj ) . length ;
7
7
}
8
8
9
+ interface RemovalOptions {
10
+ removeAllFalsy ?: boolean ;
11
+ }
12
+
9
13
// Modified from here: https://stackoverflow.com/a/43781499
10
- function stripEmptyObjects ( obj : any ) {
14
+ function stripEmptyObjects ( obj : any , options : RemovalOptions = { } ) {
11
15
const cleanObj = obj ;
12
16
17
+ if ( obj === null && options . removeAllFalsy ) {
18
+ return undefined ;
19
+ }
20
+
13
21
if ( ! isObject ( obj ) && ! Array . isArray ( cleanObj ) ) {
14
22
return cleanObj ;
15
- } else if ( obj === null ) {
16
- return undefined ;
17
23
}
18
24
19
25
if ( ! Array . isArray ( cleanObj ) ) {
20
26
Object . keys ( cleanObj ) . forEach ( key => {
21
27
let value = cleanObj [ key ] ;
22
28
23
- if ( typeof value === 'object' && value !== null ) {
24
- value = stripEmptyObjects ( value ) ;
29
+ if ( typeof value !== 'object' ) {
30
+ return ;
31
+ }
25
32
26
- if ( isEmptyObject ( value ) ) {
33
+ if ( value === null ) {
34
+ if ( options . removeAllFalsy ) {
27
35
delete cleanObj [ key ] ;
28
- } else {
29
- cleanObj [ key ] = value ;
30
36
}
31
- } else if ( value === null ) {
32
- // Null properties in an object should remain!
37
+ return ;
38
+ }
39
+
40
+ value = stripEmptyObjects ( value , options ) ;
41
+
42
+ if ( isEmptyObject ( value ) ) {
43
+ delete cleanObj [ key ] ;
44
+ } else {
45
+ cleanObj [ key ] = value ;
33
46
}
34
47
} ) ;
35
48
@@ -39,7 +52,7 @@ function stripEmptyObjects(obj: any) {
39
52
cleanObj . forEach ( ( o , idx ) => {
40
53
let value = o ;
41
54
if ( typeof value === 'object' && value !== null ) {
42
- value = stripEmptyObjects ( value ) ;
55
+ value = stripEmptyObjects ( value , options ) ;
43
56
44
57
if ( isEmptyObject ( value ) ) {
45
58
delete cleanObj [ idx ] ;
@@ -57,7 +70,7 @@ function stripEmptyObjects(obj: any) {
57
70
return cleanObj . filter ( el => el !== undefined ) ;
58
71
}
59
72
60
- export default function removeUndefinedObjects < T > ( obj ?: T ) : T | undefined {
73
+ export default function removeUndefinedObjects < T > ( obj ?: T , options ?: RemovalOptions ) : T | undefined {
61
74
if ( obj === undefined ) {
62
75
return undefined ;
63
76
}
@@ -68,7 +81,7 @@ export default function removeUndefinedObjects<T>(obj?: T): T | undefined {
68
81
let withoutUndefined = JSON . parse ( JSON . stringify ( obj ) ) ;
69
82
70
83
// Then we recursively remove all empty objects and nullish arrays.
71
- withoutUndefined = stripEmptyObjects ( withoutUndefined ) ;
84
+ withoutUndefined = stripEmptyObjects ( withoutUndefined , options ) ;
72
85
73
86
// If the only thing that's leftover is an empty object then return nothing.
74
87
if ( isEmptyObject ( withoutUndefined ) ) return undefined ;
0 commit comments