function removeKeysByCondition(obj: any, condition: (value: any) => boolean): any {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
const newObj: any = Array.isArray(obj) ? [] : {};
Object.keys(obj).forEach(key => {
if (condition(obj[key])) {
} else if (typeof obj[key] === 'object') {
newObj[key] = removeKeysByCondition(obj[key], condition);
} else {
newObj[key] = obj[key];
}
});
return newObj;
}
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);