Looping through Objects

In the last article we talked about how you can use loops to iterate over/through the contents of an Array or String. So let's continue and see how we can iterate through the contents of an Object in JavaScript.

Iterate through an Object

The first way we are going to learn is using the for...in loop. The for...in loops through the objects properties in the prototype chain. If you're confused by what the prototype chain is, don't worry. You don't need to know what it is to understand how to use the loop. But if you are interested take a look at this article explain JavaScript's prototype chain like I'm five.

Let's take a look at some code shall we?

for...in syntax:

for (key in object) {
    // body of loop
}

Ok sure, but how do we use it? Examples are good things:

let userObj = {
    name: "Dan",
    email: "Dan@company.net",
    department: "Engineering",
    role: "Web Developer"
}

for(let key in userObj) {
    console.log(key);
}

/* Output -> "name"
             "email"
             "department"
             "role"              */

Notice what we got from logging out the key at each iteration through the loop? Well that is pretty obvious isn't it, we get each key of the key : value pair.

So how do we get the value?

Excellent question, how do we get the value out using this method?

Do you remember how we can access values from an object? If we have the key we can take a peek at the value being held using obj[key] // Output -> value. How about some more code to explore this further?

let userObj = {
    name: "Dan",
    email: "Dan@company.net",
    department: "Engineering",
    role: "Web Developer"
}

for(let key in userObj) {
    console.log(`${key} : ${userObj[key]}`);
}

/* Output -> "name : Dan"
             "email : Dan@company.net"
             "department: Engineering"
             "role: Web Developer"          */

Cool right? Now we can loop through the contents of an object and check to see if it has a particular property belonging to it.

Notice anything else? You may not often see it, but it is worth noting that when you are looping through the contents of an Object you are not always given them in order.

Convert an Object into an Array

As is often the case and we have mentioned here before, there is more than one way to accomplish a task in programming. So let us explore some other methods that were added as part of the ES6+ updates.

Object Methods:

  • Object.keys()
  • Object.values()
  • Object.entries()

All of these methods will take an object passed to them and will and convert it into an array. Once we have this new array object, we can use any of the previous looping methods that we have learned in the last article and loop through the contexts to find the data we are looking for.

let userObj = {
    name: "Dan",
    email: "Dan@company.net",
    department: "Engineering",
    role: "Web Developer"
}

let keysArray = Object.keys(userObj);
console.log(keysArray);  // Output -> ["name", "email", "department", "role"]

let valuesArray = Object.values(userObject);
console.log(valuesArray);  // Output -> ["Dan", "Dan@company.net", "Engineering", "Web Developer"]

let entriesArray = Object.entries(userObject);
console.log(entriesArray);  // // Output -> [["name", "Dan"], ["email", "Dan@company.net"], ["department", "Engineering"], ["role", "Web Developer"]]

Let's talk about what is happening in the code above. We start with defining our object. The first method Object.keys(userObject) loops through the User object argument passed in and takes each key from the object, and adds it to an array that we defined as keysArray. If you log the output you can see that we now have all of the keys of the userObject as values in the new array. Pretty much the same thing happens with the following method Object.values(userObject), we just push the values to the valuesArray instead of the keys.

In the last method, Object.entries(userObject) actually creates an array of arrays from the data contained in the userObject that we defined.

You may or may not have heard of this before, but a common thing I remember being taught as a new JS programmer is that "Almost, Everything in JavaScript is an Object". The reason behind this saying is that other than Primitive Data Types(String, Boolean, Number, Boolean, BigInt, Symbol, Null, Undefined), pretty much everything else is of type Object in JavaScript. The three methods we used in the code above belong to the Object Data Type. There are more than just the three we are looking at here, but that's for another time. Here's a good resource to learn more.

for...of vs for...in:

Now that we have learned a little about for...of and for...in loops, I wanted to briefly provide a few differences between the two.

for...of:

  • The for...of loop is used to iterate through the values of an iterable.
  • The for...of loop cannot be used to iterate over an object.

for...in:

  • The for...in loop is used to iterate through the keys of an object.
  • You can use for...in to iterate over an iterable such arrays and strings but you should avoid using it in favor of a for...of loop.

Hopefully this article on looping through Objects in JavaScript was useful to you. Thanks for reading, until next time!