If you're trying to remove all "falsy" properties from an object, then this code should do:
function removeFalsyProps(obj) {
for (var key in obj) {
if(!obj[key]) {
delete obj[key];
}
}
return obj;
}
Try calling above function with below object:
{ name: "Emmanuel", age: 24, isFalse: false, isNull: null, country: "Nigeria" }
This will adjust the object so all falsy properties are removed:
{ name: "Emmanuel", age: 24, country: "Nigeria" }
Please note that as JavaScript treats objects by reference, the object you pass to removeFalsyProps
is adjusted, i.e. there is no need to actually return it, as I do in my code. I just think it's more explicit that way. In case you don't want to change the original object, you should consider copying/cloning it first.
Please also be aware that if you have a property like count: 0
, that will be removed as well, as 0
is falsy.. But maybe this is desired behavior?
Additionally (depending on your object-structure, -inheritance and -creation), you might want to do the hasOwnProperty
-check. See MDN or this post or this blog post for additional information.