Last active
March 24, 2022 23:27
-
-
Save JeanPaulll/a172ad426d6a7da62ede934ac25e1312 to your computer and use it in GitHub Desktop.
Function to handle payload
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
private treatObjectToSend(obj: { [key: string]: any }): { [key: string]: any; } { | |
let finalObject = Object.assign({}, obj); | |
let count = 1; | |
const removePropertiesNull = ( | |
data: { [key: string]: any } = {} | |
): { [key: string]: any } => { | |
const _data = {}; | |
Object.keys(data).forEach((r) => { | |
if ( | |
(data[r] != null && Object.keys(data[r]).length) || | |
typeof data[r] === 'number' || | |
typeof data[r] === 'boolean' | |
) { | |
_data[r] = data[r]; | |
} | |
}); | |
return _data; | |
}; | |
const removeEmptyArrays = (arr: any[]): any[] => { | |
const _arr = []; | |
if (arr === null || !Array.isArray(arr)) { | |
return; | |
} | |
arr.forEach((item, index: number) => { | |
if (Array.isArray(item)) { | |
_arr.push(removeEmptyArrays(item)); | |
} else { | |
if (!Object.keys(arr[index]).length) { | |
return; | |
} else { | |
const ps = removePropertiesNull(this.treatObjectToSend(arr[index])); | |
if (Object.keys(ps).length) { | |
_arr.push(ps); | |
} | |
} | |
} | |
}); | |
return _arr; | |
}; | |
const removeInvalidPropertie = ( | |
data: { [key: string]: any } = {}, | |
key: string | |
): { [key: string]: any } => { | |
if (data[key] === null) { | |
delete data[key]; | |
} | |
if ( | |
(data[key] != null && Object.keys(data[key]).length) || | |
typeof data[key] === 'number' || | |
typeof data[key] === 'boolean' | |
) { | |
return; | |
} | |
delete data[key]; | |
}; | |
const treatObj = (_o: { [key: string]: any }): { [key: string]: any } => { | |
const o = Object.assign({}, _o); | |
Object.keys(o).forEach((r) => { | |
removeInvalidPropertie(o, r); | |
if (Array.isArray(o[r])) { | |
o[r] = o[r].map((i) => treatObj(i)); | |
} else if (typeof o[r] === 'object') { | |
o[r] = treatObj(o[r]); | |
} | |
}); | |
return o; | |
}; | |
if (Object.keys(finalObject).length) { | |
finalObject = removePropertiesNull(finalObject); | |
Object.keys(finalObject).forEach((r) => { | |
if ( | |
Array.isArray(finalObject[r]) && | |
finalObject[r].length && | |
typeof finalObject[r] === 'object' | |
) { | |
if (Array.isArray(finalObject[r]) && finalObject[r].length) { | |
if (Object.keys(finalObject[r]).length > 0) { | |
finalObject[r] = removeEmptyArrays(finalObject[r]); | |
} | |
} | |
} | |
count++; | |
}); | |
if ( | |
typeof finalObject === 'object' && | |
Object.keys(finalObject).length > 0 | |
) { | |
for (let i = 0; i <= count; i++) { | |
finalObject = treatObj(finalObject); | |
} | |
} | |
return finalObject; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment