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;
}
CodePudding user response:
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))
CodePudding user response:
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 ||
.