@@ -8,41 +8,55 @@ function isEmptyObject(obj: unknown) {
8
8
9
9
// Modified from here: https://stackoverflow.com/a/43781499
10
10
function stripEmptyObjects ( obj : any ) {
11
- let cleanObj = obj ;
11
+ const cleanObj = obj ;
12
12
13
13
if ( ! isObject ( obj ) && ! Array . isArray ( cleanObj ) ) {
14
14
return cleanObj ;
15
15
} else if ( obj === null ) {
16
16
return undefined ;
17
17
}
18
18
19
- Object . keys ( cleanObj ) . forEach ( key => {
20
- let value = cleanObj [ key ] ;
19
+ if ( ! Array . isArray ( cleanObj ) ) {
20
+ Object . keys ( cleanObj ) . forEach ( key => {
21
+ let value = cleanObj [ key ] ;
21
22
22
- if ( typeof value === 'object' && ! Array . isArray ( cleanObj ) && value !== null ) {
23
- // Recurse, strip out empty objects from children
23
+ if ( typeof value === 'object' && value !== null ) {
24
+ value = stripEmptyObjects ( value ) ;
25
+
26
+ if ( isEmptyObject ( value ) ) {
27
+ delete cleanObj [ key ] ;
28
+ } else {
29
+ cleanObj [ key ] = value ;
30
+ }
31
+ } else if ( value === null ) {
32
+ // Null properties in an object should remain!
33
+ }
34
+ } ) ;
35
+
36
+ return cleanObj ;
37
+ }
38
+
39
+ cleanObj . forEach ( ( o , idx ) => {
40
+ let value = o ;
41
+ if ( typeof value === 'object' && value !== null ) {
24
42
value = stripEmptyObjects ( value ) ;
25
43
26
- // Then remove all empty objects from the top level object
27
44
if ( isEmptyObject ( value ) ) {
28
- delete cleanObj [ key ] ;
45
+ delete cleanObj [ idx ] ;
29
46
} else {
30
- cleanObj [ key ] = value ;
47
+ cleanObj [ idx ] = value ;
31
48
}
32
49
} else if ( value === null ) {
33
- delete cleanObj [ key ] ;
50
+ // Null entries within an array should be removed.
51
+ delete cleanObj [ idx ] ;
34
52
}
35
53
} ) ;
36
54
37
- if ( Array . isArray ( cleanObj ) ) {
38
- // Since deleting a key from an array will retain an undefined value in that array, we need to
39
- // filter them out.
40
- cleanObj = cleanObj . filter ( function ( el ) {
41
- return el !== undefined ;
42
- } ) ;
43
- }
44
-
45
- return cleanObj ;
55
+ // Since deleting a key from an array will retain an undefined value in that array, we need to
56
+ // filter them out.
57
+ return cleanObj . filter ( function ( el ) {
58
+ return el !== undefined ;
59
+ } ) ;
46
60
}
47
61
48
62
export default function removeUndefinedObjects ( obj ?: unknown ) {
0 commit comments