1
0
mirror of https://github.com/dzeiocom/libs.git synced 2025-07-29 16:29:52 +00:00

feat: Add option to clean falsy values in object clean

Add a new option to `objectClean` function which allows to clean falsy values (including `undefined` and `null`) from an object when set to `true`. This is achieved by deleting all the falsy values from the object when the option is enabled.

The change also includes updates to the corresponding tests.

Signed-off-by: Avior <f.bouillon@aptatio.com>
This commit is contained in:
2023-03-14 11:00:19 +01:00
parent fd24924d10
commit 446355b451
2 changed files with 28 additions and 10 deletions

View File

@ -256,27 +256,29 @@ export function objectEqual(first: BasicObject, second: BasicObject): boolean {
}
/**
* Deeply clean an object from having `undefined` and/or `null` (option to enable)
* Deeply clean an object from having `undefined`,`null` and/or flasy values (options to enable)
*
* @param obj the object to clean
* @param options cleanup options
* @param {boolean?} options.cleanUndefined (default: true) clean undefined from the object
* @param {boolean?} options.cleanFalsy (default: false) clean falsy values (including undefined and null) from the object see https://developer.mozilla.org/en-US/docs/Glossary/Falsy
* @param {boolean?} options.cleanNull (default: false) clean null from the object
* @param {boolean?} options.deep (default: true) deeply clean the object
*/
export function objectClean(obj: BasicObject, options?: {cleanUndefined?: boolean, cleanNull?: boolean, deep?: boolean}): void {
export function objectClean(obj: BasicObject, options?: {cleanUndefined?: boolean, cleanNull?: boolean, cleanFalsy?: boolean, deep?: boolean}): void {
mustBeObject(obj)
objectLoop(obj, (item, key) => {
if ((typeof options?.cleanUndefined === 'undefined' || options?.cleanUndefined) && item === undefined) {
delete obj[key]
if ((typeof options?.cleanUndefined === 'undefined' || options.cleanUndefined) && item === undefined) {
delete obj[key] // clean undefined values
} else if (options?.cleanFalsy && !obj[key]) {
delete obj[key] // clean falsy values
} else if (options?.cleanNull && item === null) {
delete obj[key] // clean null values
}
if (options?.cleanNull && item === null) {
delete obj[key]
}
if ((typeof options?.deep === 'undefined' || options?.deep) && isObject(item)) {
return objectClean(item, options)
// deeply clean the object
if ((typeof options?.deep === 'undefined' || options.deep) && isObject(item)) {
objectClean(item, options)
}
})
}