Skip to content

Commit 66915cc

Browse files
authored
fix: allowing null object properties to remain (#8)
1 parent e6684da commit 66915cc

File tree

2 files changed

+35
-18
lines changed

2 files changed

+35
-18
lines changed

__tests__/index.test.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,13 @@ test('should remove empty arrays from within object', () => {
4444
},
4545
d: [1234, undefined],
4646
e: [],
47+
f: null,
48+
g: [null, undefined, null],
4749
};
4850

4951
expect(removeUndefinedObjects(obj)).toStrictEqual({
5052
d: [1234],
53+
f: null,
5154
});
5255
});
5356

src/index.ts

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,41 +8,55 @@ function isEmptyObject(obj: unknown) {
88

99
// Modified from here: https://stackoverflow.com/a/43781499
1010
function stripEmptyObjects(obj: any) {
11-
let cleanObj = obj;
11+
const cleanObj = obj;
1212

1313
if (!isObject(obj) && !Array.isArray(cleanObj)) {
1414
return cleanObj;
1515
} else if (obj === null) {
1616
return undefined;
1717
}
1818

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];
2122

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) {
2442
value = stripEmptyObjects(value);
2543

26-
// Then remove all empty objects from the top level object
2744
if (isEmptyObject(value)) {
28-
delete cleanObj[key];
45+
delete cleanObj[idx];
2946
} else {
30-
cleanObj[key] = value;
47+
cleanObj[idx] = value;
3148
}
3249
} else if (value === null) {
33-
delete cleanObj[key];
50+
// Null entries within an array should be removed.
51+
delete cleanObj[idx];
3452
}
3553
});
3654

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+
});
4660
}
4761

4862
export default function removeUndefinedObjects(obj?: unknown) {

0 commit comments

Comments
 (0)