0

I'm trying to create a function called onlyTruthy that takes in an object, loops through all its properties, and removes any that are falsy. Then return the object that was passed in.

The following code keeps failing and I'm not sure what I'm doing wrong..

var onlyTruthy = function(someObject){
  for(var property in someObject){
    if(someObject[property] == "false"){
      delete someObject.property;
    }
  }
  return someObject;
};
just_be_kind
  • 51
  • 1
  • 3

1 Answers1

4

There are two main issues going on here:

  1. 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.

  2. 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)));
Kanish
  • 273
  • 4
  • 10
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Gotcha! Your explanation definitely deepen my understanding. Using your code, it still fails for some reason.. `var someObject = {name:"ernest", age:50, funky:false, foo:bar, foo2:""};` should become `{name:"ernest", age:50, foo:bar}` – just_be_kind May 04 '16 at 00:56
  • @just_be_kind - You also had to change from `delete someObject.property` to `delete someObject[property]`. There's a working demo in my answer now. – jfriend00 May 04 '16 at 00:57
  • @jfriend00 Done! :-) – just_be_kind May 04 '16 at 05:31