Last active
October 24, 2023 17:04
-
-
Save essejmclean/cd461c2a5208601dc6ec5c8c6e99b3f3 to your computer and use it in GitHub Desktop.
Filter Null and Undefined Values from Nested Objects and Arrays in TypeScript
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
/** | |
* Filters out null and undefined values from the given object or array, including nested objects and arrays. | |
* @param {T} inputObj - The input object or array to filter. | |
* @returns {Required<{ [K in keyof T]: NonNullable<T[K]> }>} - A new object or array with the same structure as the input, but with all null and undefined values removed. | |
* @template T - The type of the input object or array, extending Record<string, any> or any[]. | |
*/ | |
export function filterNullAndUndefined<T extends Record<string, any> | any[]>( | |
inputObj: T, | |
): Required<{ [K in keyof T]: NonNullable<T[K]> }> { | |
if (typeof inputObj !== "object" || inputObj === null) { | |
return inputObj as Required<{ [K in keyof T]: NonNullable<T[K]> }>; | |
} | |
const result: any = {}; | |
for (const key of Object.keys(inputObj) as Array<keyof T>) { | |
const value = inputObj[key]; | |
if (value !== null && value !== undefined) { | |
if (Array.isArray(value)) { | |
result[key] = value.reduce((acc, item) => { | |
if (item !== null && item !== undefined) { | |
acc.push(filterNullAndUndefined(item)); | |
} | |
return acc; | |
}, []); | |
} else if (typeof value === "object") { | |
result[key] = filterNullAndUndefined(value); | |
} else { | |
result[key] = value; | |
} | |
} | |
} | |
return result as Required<{ [K in keyof T]: NonNullable<T[K]> }>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment