How to iterate over a JavaScript object

In this shot, we will learn how to iterate over a JavaScript object.

The Object.entries method will return the key-value pairs for an object that is passed as a parameter to it.

We will try to iterate those returned key-value pairs using the following methods:

  • Using a for loop
  • Using a for-each loop

Using a for loop

//declare an object
obj = { '1': 'apple',
'2': 'orange',
'3': 'grapes',
'4': 'guava',
'5': 'watermelon' }
//Using for of loop to iterate
for(const [key,value] of Object.entries(obj)){
//print key and value pairs
//transform the value to uppercase
console.log(key,value.toUpperCase())
}

Explanation

In the above code snippet:

  • Line 2: We declared and initialized an object obj.
  • Line 9: We used a for loop to iterate through the key-value pairs returned by Object.entries(obj).
  • Line 12: We transformed the value to uppercase and printed the key and value pairs of the given object.

Using a for-each loop

//declare an object
obj = { '1': 'apple',
'2': 'orange',
'3': 'grapes',
'4': 'guava',
'5': 'watermelon' }
//Use Object.entries and forEach loop to traverse the object
Object.entries(obj).forEach(
([key,value])=>{
//print key and value pairs
//transform the value to uppercase
console.log(key,value.toUpperCase())
}
)

Explanation

In the above code snippet:

  • Line 2: We declared and initialized an object obj.
  • Line 9: We used a forEach loop and lambda function to iterate through the key-value pairs returned by Object.entries(obj).
  • Line 10: We destructured the [key, value] as distinct variables.
  • Line 13: We transformed the value to uppercase and printed the key and value pairs of the given object.