0

//Is there a better way to determine if a property is 'True' or 'False'

function truthyObjLoop(user){
    user = {name:"Emmanuel", age:24, country:"Nigeria"};

    for (var key in user) {
        if (user[key])
            return user[key];
      }
      delete user[key];
}

truthyObjLoop();
radical7
  • 8,957
  • 3
  • 24
  • 33
  • Your code iterates through the `user`-properties and deletes all of the falsy ones, until the first truthy one is reached, which is then returned. Is this really what you want to do? Your question is something different, as far as I understand..? – PzYon Sep 22 '15 at 22:10
  • I am trying to Loop through the user object checking to make sure that each value is truthy. If it's not truthy, remove it from the object. and use delete – Emmanuel Ezejiofo Sep 22 '15 at 22:12
  • @Blazemonger how can I define better – Emmanuel Ezejiofo Sep 22 '15 at 22:12
  • @PzYon Thanks for the help. I really appreciate it. – Emmanuel Ezejiofo Sep 23 '15 at 00:59
  • @EmmanuelEzejiofo: You're welcome. If you're happy with the answer and don't have any further questions, then you can "close" the question by selecting an answer. – PzYon Sep 23 '15 at 04:54
  • @PzYon I am tryng to understand .hasOwnProperty(), where can I go to do so. – Emmanuel Ezejiofo Sep 23 '15 at 05:35
  • @EmmanuelEzejiofo: I updated my post with some links.. I would start by reading the blog post then making some simple examples, to get the hang of it. – PzYon Sep 23 '15 at 05:47

1 Answers1

1

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.

Community
  • 1
  • 1
PzYon
  • 2,963
  • 3
  • 16
  • 27