How can i modify the blow sample code to not only check for empty Keys but also null and undefined.
I tried
(obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined)
but that broke it and didnt work at all so if i use either condition it will work but not when all together. So i am wondering how i can combine it all 3 conditions in this code.
const removeEmpty = (obj) => {
let newObj = {};
Object.keys(obj).forEach((key) => {
if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
else if (obj[key] !== '') newObj[key] = obj[key];
});
return newObj;
}
var obj = {
Sale: {
homeownerExemption: '',
lastContractDate: '',
lastSaleBookNumber: undefined,
lastSaleDate: null,
saleType: 'Full Sale',
salesPrice: '785000',
salesPriceCode: 'Sales Price Will Be Computed',
seller1FName: '',
seller1IdCode: '',
seller1FirstName: 'Steve',
seller1LastName: 'Miller',
seller2FirstName: '',
seller2LastName: '',
transferType: 'Grant Deed',
lastTransactionRecordingDate: '7/8/2021'
},
contact: [{
name: 'Tom',
age: '',
sex: 'male'
}]
};
const removeEmpty = (obj) => {
let newObj = {};
Object.keys(obj).forEach((key) => {
if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
else if (!(obj[key] === "" || obj[key] === null || obj[key] === undefined)) newObj[key] = obj[key];
});
return newObj;
};
let test = removeEmpty(obj)
console.log(test)
If obj[key] === "", then it's not equal to null or undefined. So the second and third parts of your condition pass.
Try
if (!(obj[key] === "" || obj[key] === null || obj[key] === undefined))
You need to parenthesize the condition properly. Don't be cheap out on the parens, they're free! A reasonable way could be like this:
((obj[key] !== '') || (obj[key] !== null) || (obj[key] !== undefined))
Your condition has an extra ( after second ||.