Categories:Viewed: 91 - Published at: 9 months ago

Introduction

When writing JavaScript code, you may need to loop through JavaScript objects and enumerate their fields/values. Unfortunately, JavaScript objects are not iterable like arrays or strings, so we can't just loop an object using map(), forEach() or a for…of loop. Suppose we have an object which contains a user details:

let user = { firstName: "Jacob", lastName: "Black", age: 15, hobby: "Singing" };

If we attempt to loop through, just as we do for other iterable like arrays, colorful bug messages await:

user.map(detail => {
    console.log(detail);
}) // TypeError: user.map is not a function 

// Or
user.forEach(detail => {
    console.log(detail);
}) // TypeError: user.forEach is not a function

// Or
for (let detail of user) {
    console.log(detail);
} // TypeError: user is not iterable 
In this guide, we will take a look at how to loop and enumerate objects in JavaScript - from the simpler approaches, such as using a for...in loop to the new object static methods that were introduced in ES6 and ES8.

Loop and Enumerate Object with for...in Loop

Prior to the introduction of ES6, the only way to loop through objects in JavaScript was to obtain key-value through the use of a for...in loop. This method is supported by all modern and old browsers, and works reasonably well. Suppose we have a user object:

const user = {
    firstName: "John",
    lastName: "Doe",
    email: "[email protected]",
    age: 37,
    hobby: "Singing"
};

To iterate and enumerate the values, we can loop through each key in the user, keeping track of an index:

var index = 0;
for (const key in user) {
  if (user.hasOwnProperty(key)) {
        console.log(`Index: ${index}, ${key}: ${user[key]}`);
        index++;
    }
}

This results in:

Index: 0, firstName: John
Index: 1, lastName: Doe
Index: 2, email: [email protected]
Index: 3, age: 37
Index: 4, hobby: Singing

The for...in loop works great, but it has a flaw in that it iterates through properties in the Prototype chain, which has many other properties besides the user's. When looping through objects with the for...in loop, you must check if the property belongs to the object using hasOwnProperty(), as shown in the example above. This is both inefficient, as more looping is done than needs to be, and makes the code less readable. Secondly, sometimes you may need a little more flexibility, which arrays provide. Let’s now consider a better way with a far better syntax which works with fewer technicalities.

Object Static Methods to Loop and Enumerate JavaScript Objects

In this section, we will cover three object static methods for converting object properties to arrays. Once converted to an array - we have much more flexibility, as well as efficiency in looping through arrays and enumerating them!

  • Object.keys()
  • Object.values()
  • Object.entries()
Note: An object has properties, which are key-value pairs. Each property in an object has a name (also known as a key) and a corresponding value (also known as a value). You can extract keys() and values() individually, or entries(), which are key-value pairs, depending on which properties you'd like to enumerate.
        <h4 id="loopandenumerateobjectkeyswithobjectkeys">Loop and Enumerate Object Keys with Object.keys()</h4>

The Object.keys() method was added in ES6 to make looping over objects easier. It generates an array whose elements are strings containing the names (keys) of an object's properties. The object is passed as an argument to Object.keys(). After that, you can iterate through the array and retrieve the value of each property using any of the array looping methods, such as forEach(), map(), etc.

Object.keys(objectName);

For example, suppose we have an object of user scores in various subjects:

const userScores = {
    chemistry: 60,
    mathematics: 70,
    physics: 80,
    english: 98
};

We can loop through the object and fetch the keys, which for this example would be the subjects:

const names = Object.keys(userScores);
console.log(names); // ["chemistry","mathematics","physics","english"]

You will notice that this returned an array, which we can now make use of any array method to retrieve the data:

names.forEach((key, index) => {
    console.log(`${index}: ${key}`);
});

This results in:

0: chemistry
1: mathematics
2: physics
3: english

It's worth noting that you can also get the value using this notation - by supplying the key to the object:

names.forEach((key, index) => {
    console.log(`${index} - Key: ${key}, Value: ${userScores[key]}`);
});
0 - Key: chemistry, Value: 60
1 - Key: mathematics, Value: 70
2 - Key: physics, Value: 80
3 - Key: english, Value: 98

Loop and Enumerate Object Values with Object.values()

The Object.values() method is similar to Object.keys() in that it extracts the values of the object's properties, and was introduced in ES8. The returned array can then be looped through using any of the array looping methods, naturally.

Object.values(objectName);

Using the same object:

const userScores = {
    chemistry: 60,
    mathematics: 70,
    physics: 80,
    english: 98
};

The values are easily obtained through:

const values = Object.values(userScores);
console.log(values); // [60,70,80,98]

Again, we could easily loop through this array, assigning an index to each value:

values.forEach((value, index) => {
    console.log(`Index: ${index}, Value: ${value}`);
});

This results in:

Index: 0, Value: 60
Index: 1, Value: 70
Index: 2, Value: 80
Index: 3, Value: 98

Loop and Enumerate Object Properties with Object.entries()

The Object.entries() method is a hybrid of the Object.key() and Object.values() methods, producing an array of arrays with two elements in each inner array - the first element being the property, and the second element being the value. It is another ES8 method:

Object.entries(objectName);

Now, let's re-use the same object as before:

const userScores = {
    chemistry: 60,
    mathematics: 70,
    physics: 80,
    english: 98
};

We can loop through the object and fetch both the keys and the values

const data = Object.entries(userScores);
console.log(data); 

// Output:
// [
// [ "chemistry", 60 ]
// [ "mathematics", 70 ]
// [ "physics", 80 ]
// [ "english", 98 ]
// ]

The return type can be packed into a [key, value] result each, and we can still keep track of the indexing easily:

data.forEach(([key, value], index) => {
    console.log(`Index: ${index} | I scored ${value} in my ${key} subject!`)
})

This results in:

Index: 0 | I scored 60 in my chemistry subject!
Index: 1 | I scored 70 in my mathematics subject!
Index: 2 | I scored 80 in my physics subject!
Index: 3 | I scored 98 in my english subject!

This approach can accommodate more manipulations and computation, as we have access to both the keys and the values.

Conclusion

In this guide, we've taken a look at how to loop through objects and enumerate their properties. We've started out with the simple for...in loop, noting its limitations. Then, we've jumped into looping and enumeration of values, keys and the pairs of values and keys using static Object methods, added in ES6 and ES8.

Reference: stackabuse.com

TAGS :