Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Loop over an Object with for...in, Object.keys, Object.values, and Object.entries

    Chris AchardChris Achard

    In Javascript, there are several ways you can iterate over an object's keys and values. We'll look at for...in, which will loop over all the keys (though you may need to also use hasOwnProperty). We'll also look at three built in object functions: keys, values, and entries.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 If we have an object, we can loop over the object with a for-in statement, because objects are enumerable. That will loop over all the keys in the object. We can print the keys and access the value for each key from the object, which prints all the keys and the values in our object.

    00:21 There are two things to watch out for when using for-in, however. First, you'll see I'm declaring the key as a new const. If we didn't have a const or a let there, it would still work, but then the key variable would be creating a new global variable.

    00:38 That value would leak outside of the loop, which is probably not what I want to do. Also, a for-in loop will look at all the properties in the prototype chain. That doesn't matter in this case, since we just have a simple object, but you can protect against that by checking if the object has the key as its own property before doing something with that key.

    01:04 We could also choose to loop over the object by calling object.keys first, which returns an array of all the keys in the object. We could loop over the key array with forEach, and do something with that key and the value from the object.

    01:22 Or we could map over the keys, then create an array, and do something with the resulting array later. If we're just interested in looping over the values from an object, we could use object.values instead.

    01:43 Finally, if we know that we want both the keys and values, we can get both at once using object.entries. You can see that each entry is an array, with the first element being the key and the second element being the value.

    02:02 We could extract the key and the value from that array, or we could destructure that in the function argument list itself, which gives us a clean way to extract the key and the value for every pair in the object.

    Discuss

    Discuss