Last active
June 11, 2021 17:24
-
-
Save kcak11/623da34817b60e90ab00168e96b132a2 to your computer and use it in GitHub Desktop.
Trim Payload
This file contains hidden or 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
/** | |
* Trim Payload | |
* | |
* @Params: | |
* payload: The payload object to be trimmed. | |
* options: Optional configuraton object with following possible config(s): | |
* preserveEmptyItemsInArray: true --> Implies that if the payload object contains arrays with '<empty-string>' values, then retain them. | |
* | |
* Definition of '<empty-string>': | |
* - Any string that after a .trim() operation, is empty e.g.: " " or "\n\n\n\n" or " \n \n " (a string with just spaces or line-breaks or both). | |
*/ | |
function trimPayload(payload, options) { | |
try { | |
return JSON.parse(JSON.stringify(payload, function (k, v) { | |
if (typeof v === "string" && v) { | |
if (this instanceof Array) { | |
if (options && options.preserveEmptyItemsInArray === true) { | |
return v.trim() ? v.trim() : v; | |
} | |
return v.trim(); | |
} else { | |
return v.trim(); | |
} | |
} else if (v && (v instanceof Array)) { | |
if (options && options.preserveEmptyItemsInArray === true) { | |
return v; | |
} else { | |
return v.filter(function (item) { | |
if ((item && typeof item === "string") || item === "") { | |
return !!item.trim(); | |
} else { | |
return true; | |
} | |
}); | |
} | |
} else { | |
return v; | |
} | |
})); | |
} catch (exjs) { | |
return payload; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment