When writing JavaScript programs, you may have come across situations where you want to loop over an object, just as you would with arrays or strings. But objects are not iterables by default in JavaScript. Objects cannot be looped over in the same way as arrays and strings because they do not have a built-in length property.

//iterating arrays
let numbers= [13, 10, 56];

numbers.forEach((num) => console.log(num)); // ✅✅✅


for (num of numbers) {
  console.log(num); // ✅✅✅
}


//iterating objects
let userProfile = { age: 30, name: "John Doe" };

userProfile.forEach((user) => console.log(user)); // ❌❌❌

for (user of userProfile) {
  console.log(user); // ❌❌❌
}

In this article, you will learn how to iterate over JavaScript objects.

How to iterate over JavaScript objects

In order to iterate over a JavaScript object’s properties, you will need to use specific methods or techniques. The most common and traditional method used is for… in loop.

Here is an example of how to use a for… in loop to iterate an object

const user = {
  name: "John Doe",
  age: 30,
  city: "New York"
};
 
for (const property in user) {

     console.log(`${property}: ${user[property]}`);
}
// name: John
// age: 30
// city: New York

This method is not generally considered the most efficient. This is because it iterates over the entire enumerable properties of the object, including those inherited from its prototype chain, which can lead to performance issues for objects with long prototype chains.

However, to avoid these issues, you will have to check if the property belongs to the object you intend to loop over by using the hasOwnProperty() method.

for (const property in user) {
  if (user.hasOwnProperty(property)) {
    const key = property;
    const value = user[property];

    console.log(`Key: ${key}, Value: ${value}`);
  }
}

The code iterates over the properties of the person object and explicitly outputs each key-value pair, after which the hasOwnProperty() method ensures that only properties directly belonging to the object are looped, while inheritance properties are omitted.

ES6 and ES8 introduced several alternative methods in order to avoid some of the limitations of the for… in loop.

These methods include:

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

These methods convert object properties to arrays, allowing us to use various loop methods like for loopsforEach(), map(), and others on the returned array.

Object.keys()

The Object.keys method was introduced in ES6 to provide a more efficient way to loop over objects. It takes a target object as an argument and returns an array containing the names of all the enumerable properties of the object. This array can then be used with any JavaScript loop method to iterate and retrieve the value of each property.

Here is an example of how to use the object.keys() method:

const user = {
  name: "John Doe",
  age: 30,
  city: "New York"
};

const userNames = object.keys(user);

console.log(userNames); 
// Output: ["name", "age", "city"]


//iterate over the array returns by the object.keys method
userName.forEach((key, index)=>{
   console.log(`${key}: ${user[key]}`)
}

//name: John Doe,
//age: 30,
//city: New York


Object.values()

Object.values() method is a useful tool introduced in ES8. This method takes an object as an argument and returns an array containing the values of all enumerable properties of the provided object.

Here is an example of how to use the object.values() method:

const user = {
  name: "John Doe",
  age: 30,
  city: "New York"
};

const userName = object.values(user);

console.log(userName); 
// Output: ["John Doe", 30, "New York"]


userName.forEach((value)=>{
     console.log(value)
})

// John Doe
// 30
// New York4

Object.entries()

The Object.entries() method was also introduced in ES8, and it returns an array of arrays of the object’s own property, with each subarray containing the property name as the first element and the property value as the second element.

Here is an example of how to use the

object.entries() method:const user = {
  name: "John Doe",
  age: 30,
  city: "New York"
};

const userNames = object.entries(user).forEach((entry)=>{
     console.log(entry)
})

//[ ['name', 'John Doe'], ['age', 30], ['city', 'New York'] ]

In this example, the code outputs arrays of arrays, with each subarray containing [key, value]. You can loop over the array returned by Object.entries(), using either the for…of loop or the forEach() method.

Both methods are suitable for iterating over the array and key-value pair because they’re more efficient and more readable than other array methods.

//Example of how to iterate over the array returns by the object.entries()
const user = {
  name: "John Doe",
  age: 30,
  city: "New York"
};

const userName = object.entries(user);

//iterate over userName array using for of loop method 
for (const [key, value] of userName) {
  console.log(`${key}: ${value}`);
}


//iterate over userName array using forEach method 
userName.forEach(([key, value])=>{
    console.log(`${key}: ${value}`);
})


//In this example, the both methods will output it’s individual key-value pairs.

// name: John Doe
// age: 30
// city: New York

Conclusion

In this article, you learned some of the best ways to loop through an object based on specific needs. Each of these methods returns an array before it’s finally looped over.

Stackademic

Thank you for reading until the end. Before you go:

  • Please consider clapping and following the writer! 👏
  • Follow us on Twitter(X)LinkedIn, and YouTube.
  • Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.