@@ -6,30 +6,43 @@ function isEmptyObject(obj: unknown) {
66 return typeof obj === 'object' && obj !== null && ! Object . keys ( obj ) . length ;
77}
88
9+ interface RemovalOptions {
10+ removeAllFalsy ?: boolean ;
11+ }
12+
913// Modified from here: https://stackoverflow.com/a/43781499
10- function stripEmptyObjects ( obj : any ) {
14+ function stripEmptyObjects ( obj : any , options : RemovalOptions = { } ) {
1115 const cleanObj = obj ;
1216
17+ if ( obj === null && options . removeAllFalsy ) {
18+ return undefined ;
19+ }
20+
1321 if ( ! isObject ( obj ) && ! Array . isArray ( cleanObj ) ) {
1422 return cleanObj ;
15- } else if ( obj === null ) {
16- return undefined ;
1723 }
1824
1925 if ( ! Array . isArray ( cleanObj ) ) {
2026 Object . keys ( cleanObj ) . forEach ( key => {
2127 let value = cleanObj [ key ] ;
2228
23- if ( typeof value === 'object' && value !== null ) {
24- value = stripEmptyObjects ( value ) ;
29+ if ( typeof value !== 'object' ) {
30+ return ;
31+ }
2532
26- if ( isEmptyObject ( value ) ) {
33+ if ( value === null ) {
34+ if ( options . removeAllFalsy ) {
2735 delete cleanObj [ key ] ;
28- } else {
29- cleanObj [ key ] = value ;
3036 }
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 ;
3346 }
3447 } ) ;
3548
@@ -39,7 +52,7 @@ function stripEmptyObjects(obj: any) {
3952 cleanObj . forEach ( ( o , idx ) => {
4053 let value = o ;
4154 if ( typeof value === 'object' && value !== null ) {
42- value = stripEmptyObjects ( value ) ;
55+ value = stripEmptyObjects ( value , options ) ;
4356
4457 if ( isEmptyObject ( value ) ) {
4558 delete cleanObj [ idx ] ;
@@ -57,7 +70,7 @@ function stripEmptyObjects(obj: any) {
5770 return cleanObj . filter ( el => el !== undefined ) ;
5871}
5972
60- export default function removeUndefinedObjects < T > ( obj ?: T ) : T | undefined {
73+ export default function removeUndefinedObjects < T > ( obj ?: T , options ?: RemovalOptions ) : T | undefined {
6174 if ( obj === undefined ) {
6275 return undefined ;
6376 }
@@ -68,7 +81,7 @@ export default function removeUndefinedObjects<T>(obj?: T): T | undefined {
6881 let withoutUndefined = JSON . parse ( JSON . stringify ( obj ) ) ;
6982
7083 // Then we recursively remove all empty objects and nullish arrays.
71- withoutUndefined = stripEmptyObjects ( withoutUndefined ) ;
84+ withoutUndefined = stripEmptyObjects ( withoutUndefined , options ) ;
7285
7386 // If the only thing that's leftover is an empty object then return nothing.
7487 if ( isEmptyObject ( withoutUndefined ) ) return undefined ;
0 commit comments