Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Iterating through an object in JS.

I am trying to write a function that iterates through an object, deletes falsey keys, and creates new object with new parameters.

I have been using a for...in loop and delete I am stuck though because when looking up answers there is nothing specific to my task.

Before I go into detail on this, what do you mean by "new object with new parameters"? Are these new parameters taken from the old object? Please be a little more specific in what you're attempting to do, and share the code you've already created so that we can better help you.

If you're unsure of how to post code to the forums, you can refer to this picture:

code

It's the same object that we started with, only now the falsy values are deleted. I started with a for...in loop and built in a function to check for and delete falsy key-values but it didn't work. Lo I scraped it and am back to square one.

//this is my assignment 

var user = {
    name: 'Bob Odenkirk', 
    email: null,
    pwHash: 'U+Ldlngx2BYQk',
    birthday: undefined,
    username: 'bobodenkirk33',
    age: 0
};

/*Above you're given a user object. Loop through the user 
object checking to make sure that each value is truthy. If it's not
truthy, remove it from the object. hint: 'delete'. */

for (var e in user ) {
    //check to see if truthy
    if ( user[e] !== true ) {
    //if not truthy delete
       delete user[e];

    }    
}


/*Once you get your truthy array, Change the remaining values in 
the array to be specific to you (name: 'your name', username: 'your username'), 
rather than my information. */
  //////// strangely, they go from using the term "object" to the term "array" above ////////////////

1 Answer

Alrighty, Jesse, in your comparison operator in the if-statement you can't strictly check to see if an element is not equal to true because that logic would mean that everything gets deleted out of the user object because true does not exist in any key/value pair in the object.

Instead of testing to see whether it is not equal to true, instead test to see if it exists by just inserting it into the if-statement with no comparison operators. When you just insert a variable or array/object, it checks to see that it is not empty, false, undefined, or null.

By the way, an array is an object; it is just a very specific object that only uses numbers for its keys instead of numbers or names like a standard object i.e.

//These two variables can be referenced in the exact same way.
var names = ["Bob", "Sally"];
var othernames = { 0: "Bob", 1: "Sally" };
console.log(names[1]);
console.log(othernames[1]);

Here is the fixed code for your assignment to get rid of those falsey values:

//this is my assignment 

var user = {
    name: 'Bob Odenkirk', 
    email: null,
    pwHash: 'U+Ldlngx2BYQk',
    birthday: undefined,
    username: 'bobodenkirk33',
    age: 0
};

/*Above you're given a user object. Loop through the user 
object checking to make sure that each value is truthy. If it's not
truthy, remove it from the object. hint: 'delete'. */

for (var e in user ) {
    //check to see if truthy or that it's 0, because 0 is a falsey value but I am going to assume that you'd want to change the age
    //If this isn't the case just delete this part of the if-statement: "|| user[e] === 0"
    if (user[e] || user[e] === 0) {
      //If it's a truthy value, continue on with the code
      continue;
     }
    else {
    //else if not truthy, delete it from the object
       delete user[e];
    }    
}

thanks for the point about arrays being objects. It helped me think of them in a much better way. (a special object that uses a numbered key system, that is just implicit. No need to write out the numbered keys. Awesome!)

I ran the code and it works perfect! Thank you!

I asked an old friend who programs in .NET for the most part. he threw this at me.

var user = {
    name: 'Bob Odenkirk', 
    email: null,
    pwHash: 'U+Ldlngx2BYQk',
    birthday: undefined,
    username: 'bobodenkirk33',
    age: 0
};

for (var property in user) {
    if (user.hasOwnProperty(property)) {
        if (isFalsey(user[property])) {
            delete user[property];
        }
    }
}
function isFalsey(property) {    
    if (property === false ||
       property === null ||
       property === undefined ||
       property === NaN ||
       property === 0)
    {
        return true;
    }
    return false;
}

//Once you get your truthy array, Change the remaining values in the array to be specific to you (name: 'your name', username: 'your username'), rather than my information.
//Replace with Code
user.name = "Jesse";
user.username = "Jesse0000";
//etc

This also works with . hasOwnProperty checking it and "isFalsey" function testing it.

Like: if it's false return true, if its not false return false lol. So the true causes the if statement to run in the for...in. I love it.

How important is the .hasOwnProperty in this context? I haven't learned about prototypes and such yet.

I put the .hasOwnProperty in your code and it works too, plus your code seems to have less computations than my friends.

for (var e in user ) {
    if (user.hasOwnProperty(e)) {
        if (user[e]) {
            continue;
        } else {
            delete user[e];
        }
    }    
}

I see where he is going with that, and if you wanted to turn "use strict" on for your JavaScript, his code would do very well. It does very well regardless of whether you're coding in a normal or strict JavaScript environment, but it takes up more physical space (because of all the extra characters) and would take extra time to parse because it has to parse a custom function and an extra built-in function.

The "hasOwnProperty" method is redundant (for this example) because the for loop is only going to iterate through the properties this object has. "hasOwnProperty" is useful for prototyped objects which is when you set up a base object with some default properties and then build other objects on top of it. The reason why it is useful for prototyped objects is that "hasOwnProperty" iterates only through enumerate properties that this specific object owns, not any properties that are inherited through another object. When you get to learn more about prototypes and objects, you'll understand exactly what I mean.

But, for right now, in other words, if the "user" object was coming from a prototype, "hasOwnProperty" would be useful, but in this case, it is redundant because the for loop is already only returning the properties that this object has.

This line (without the or statement):

if (user[e]) {
continue;
}

checks for any truthy values and if they are found, goes to the next iteration of the loop via the continue command. If you want an example of how continue is a very cool command to use with loops, I have a neat, little example thought up to share.

I thought of another improvement upon the code I gave you. Work is never done! lol

You actually do not need the else statement in the for loop because of the way continue works.

//this is my assignment 

var user = {
    name: 'Bob Odenkirk', 
    email: null,
    pwHash: 'U+Ldlngx2BYQk',
    birthday: undefined,
    username: 'bobodenkirk33',
    age: 0,
popsicle: NaN
};

/*Above you're given a user object. Loop through the user 
object checking to make sure that each value is truthy. If it's not
truthy, remove it from the object. hint: 'delete'. */

for (var e in user ) {
    //check to see if truthy or that it's 0, because 0 is a falsey value but I am going to assume that you'd want to change the age
    //If this isn't the case just delete this part of the if-statement: "|| user[e] === 0"
    if (user[e]) {
      //If it's a truthy value, continue on with the iteration of the loop* [edited]
      continue;
     }
    //if not truthy, delete it from the object
       delete user[e];
}