Skip to content

Instantly share code, notes, and snippets.

@ethaizone
Created February 6, 2024 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethaizone/e27d60785711b23f7a080c6ec34bbdcd to your computer and use it in GitHub Desktop.
Save ethaizone/e27d60785711b23f7a080c6ec34bbdcd to your computer and use it in GitHub Desktop.
TS function to alter value in each items and can loop if it's array.
/**
* This function recursively replaces all 'null' string values with undefined in an object or array of objects.
*
* @author Nimit Suwannagate <ethaizone@hotmail.com>
*
* @param {T} obj - The object or array of objects to process. The object's values can be of type string, number, or undefined.
* @returns {T} - The processed object or array of objects with all 'null' string values replaced with undefined.
*
* @template V - The type of the values in the object. Defaults to string | number | undefined.
* @template R - The type of the object. Defaults to Record<string, V>.
* @template T - The type of the input and output. Defaults to R[] | R.
*/
function replaceNullStringWithUndefined<V=string | number | undefined, R = Record<string, V>, T = R[] | R>(obj: T): T {
// If the input object is an array, recursively apply the replaceNullStringWithUndefined function to each item in the array.
if (Array.isArray(obj)) {
return obj.map((item: R) => replaceNullStringWithUndefined(item)) as T
}
// The function will replace all 'null' string values with undefined in each item.
// The result is cast to T, which is the type of the input and output of the function.
return Object.entries(obj as { [s: string]: V }).reduce((acc, [key, value]) => {
let newValue = value
if (value === 'null') {
newValue = undefined as V
}
return {
...acc,
[key]: newValue
};
}, {} as T);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment