This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Iterate over properties of an object with ES2017 Object.entries()

    Akash GuthaAkash Gutha

    The Object.entries() function is an addition to the ECMAscript scpec in Es2017. This allows us to iterate through the properties of an object and read the entries as keys and objects.

    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 Let's take a look at the entries object introduced in es2017. We'll make a variable world and give it some properties, continents, and oceans in this case. Now, let's make a variable called entries and capture the result of the Object.entries function into our variable.

    00:20 Now that we've captured the result, let's log this and check the result. If you look at the result carefully, you can see that you get a list of objects as a result. Each object is a list in itself and has two objects inside the list.

    00:35 The first one is the key, while the second one is the actual object, and it exactly matches the properties and values inside our world object. Now, let's take a for loop and log each entry object from the entries list. Let's take the console log statement from the bottom, cut it, and paste it into our for loop.

    00:58 Now, we'll change the entries to entry, because we want to log each entry. Now if you run this, you can see that the output is zero and one. That is because, entries is an iterable object. To get each object out of an iterable, we need to use the for-of loop.

    01:14 If we change this to of and run, you can see that we get our list of keys and objects. Now, let's pull out our key and object as separate variables using the array notation. For now, let's log only the keys and check the result. You can see that the keys match exactly each property in our world object.

    01:38 Let's also log each of our object just after our key and check the result. As expected, it prints out our key and object in each line. Let's see, if we can also capture a function that is attached to our object. We'll make a simple function and let's call it makepiece, and inside this function, we'll console log piece.

    02:01 Now, let's run our index file and check the result. You can see that we have makepiece as a key and the function as an object.

    Discuss

    Discuss