Beginners walkthrough to iterate over a JS Object
- Object.keys() — produces an array of keys of an object
- Object.values() — produces of an array values of the object(less use cases)
First, let’s begin by creating an object. We have our object user with three keys( name, age, occupation) pointing to three values(“Adam, 36, “Dog Trainer”). Pass that object into the Object.keys() method as you see below on line 7 and console.log that out.
Object.keys(user) will produce an array of the three keys: name, age, & occupation.
For Loop with Object.keys()
Let’s do some looping over an object using Object.keys(), passing in our user.
This loop will produce each key of our object pointing to it’s corresponding value:
Pass the user object, in the Object.values() method.
This will produce an array of values and typically has fewer use cases because there isn’t as much information to work with (since we are just retrieving values). See below in the screenshot we have a produced an array of the three values(“Adam”, 36, “Dog Trainer”).
The last method I will focus on is the Object.entries() method. Typically this method will be the most favorable of the three we have worked with to iterate over a JS object.
Let’s once again pass the user object into the Object.entries() method and see what will print to the console.
In the console, we get an array of three arrays printed. Within each of those arrays is a listing of the key and its value. Using this method allows us to interact and manipulate our data with a bit more gusto.:
For Loop with Object.entries()
Let’s build out a for loop now, pass the user object into this method.
This prints out to the console each key and its corresponding value:
Refactoring our Object.entries() For loop.
Now there is a bit simpler way to write a for loop with our Object.entries() method. Let’s introduce destructing to the loop. Instead of the “entry” keyword, we will pass in a “[key, value]” pair and then use those variable names in our console.log().
See that destructing will produce the same outcome as the first for loop for Object.entries() we wrote, but will make our for loop code a little cleaner to read!