This repository has been archived by the owner on Nov 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move remove-undefined-objects to a new function
We can add more edge case tests easier this way
- Loading branch information
1 parent
73932d8
commit 61c0af0
Showing
2 changed files
with
38 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
function isEmptyObject(obj) { | ||
// Then remove all empty objects from the top level object | ||
return typeof obj === 'object' && Object.keys(obj).length === 0; | ||
} | ||
|
||
// Modified from here: https://stackoverflow.com/a/43781499 | ||
function stripEmptyObjects(obj) { | ||
Object.keys(obj).forEach(key => { | ||
const value = obj[key]; | ||
if (typeof value === 'object') { | ||
// Recurse, strip out empty objects from children | ||
stripEmptyObjects(value); | ||
// Then remove all empty objects from the top level object | ||
if (isEmptyObject(value)) { | ||
delete obj[key]; | ||
} | ||
} | ||
}); | ||
} | ||
|
||
function removeUndefinedObjects(obj) { | ||
// JSON.stringify removes undefined values | ||
const withoutUndefined = JSON.parse(JSON.stringify(obj)); | ||
|
||
// Then we recursively remove all empty objects | ||
stripEmptyObjects(withoutUndefined); | ||
|
||
// If the only thing that's leftover is an empty object | ||
// then return nothing so we don't end up with default | ||
// code samples with: | ||
// --data '{}' | ||
if (isEmptyObject(withoutUndefined)) return undefined; | ||
|
||
return withoutUndefined; | ||
} | ||
|
||
module.exports = removeUndefinedObjects; |