function removeKeysByCondition(obj: any, condition: (value: any) => boolean): any { // If the value is not an object, return it directly. if (typeof obj !== 'object' || obj === null) { return obj; } // Construct a new object to avoid mutating the original one. const newObj: any = Array.isArray(obj) ? [] : {}; Object.keys(obj).forEach(key => { if (condition(obj[key])) { // Skip the key/value pair if the condition is met. } else if (typeof obj[key] === 'object') { // Recursively apply the function to nested objects. newObj[key] = removeKeysByCondition(obj[key], condition); } else { // Copy the key/value pair to the new object. newObj[key] = obj[key]; } }); return newObj; } // Example usage const exampleObject = { a: 1, b: null, c: { d: undefined, e: 2, f: { g: null, } } }; const result = removeKeysByCondition(exampleObject, value => value === null || value === undefined); console.log(result);