There are two main issues going on here:
if(someObject[property] == "false"
is checking to see if a property is actually a string "false"
. That's not doing a Boolean check or checking for a falsey
value.
When you delete the property, you have to do: delete someObject[property]
, not delete someObject.property
. What you were doing was always trying to remove a property named "property"
, not the actual value of the variable property
.
I'd suggest you change your code to this:
var onlyTruthy = function(someObject){
for(var property in someObject){
if(!someObject[property]){
delete someObject[property];
}
}
return someObject;
};
FYI, your if (someObject[property] == "false")
was checking to see if the property was a string "false"
. It wasn't a boolean check at all.
And, you have to change delete someObject.property
to delete someObject[property]
.
As for truthy and falsey. In Javascript, lots of values are falsey:
undefined
null
NaN
false
'' (empty string)
0
-0
0n (BigInt(0))
So, you don't want to compare if (x == false)
to check for falsey. You want to just do:
if (!x)
to see if the value is falsey.
Here's a working snippet:
var someObject = {"name":"ernest","age":50,"funky":false,"foo":"bar","foo2":""};
var onlyTruthy = function(obj){
for(var property in obj){
if(!someObject[property]){
delete obj[property];
}
}
return obj;
};
document.write(JSON.stringify(onlyTruthy(someObject)));