How to iterate through the object's properties in JavaScript

In JavaScript, we can iterate through the object's properties using the following methods:

1. The for...in loop:

This loop iterates over all the object's properties using the following syntax:

for (const obj in Object) {
// body
}
The syntax of for...in loop

Example

Let's see an example of the for..in loop in the code snippet below:

// create an object
const data = {
name: 'Shubham',
designation: 'Software Engineer'
}
// iterate over object
for (const obj in data) {
// print key and value on console
console.log(`${obj}: ${data[obj]}`)
}

Explanation

  • Line 2-5: We create an object named data.
  • Line 8: We use the for...in loop to iterate over the properties of the object data.
  • Line 10: We print all the keys and the values of the object data on the console.

2. Using object.entries() method:

This method returns an array of the object's properties in [key, value] format. While using the for...of loop, we can iterate over it using the following syntax.

for (const [key, value] in Object.entries(objectName)) {
// body
}
The syntax of the Object.entries() method

Example

Let's see an example of the object.entries() method in the code snippet below:

// create an object
const data = {
name: 'Shubham',
designation: 'Software Engineer'
}
// iterate over object
for (const [key, value] of Object.entries(data)) {
// print key and value on console
console.log(`${key}: ${value}`)
}

Explanation

  • Line 2-5: We create an object named data.
  • Line 8: We use the Object.entries() method to iterate over the properties of data.
  • Line 10: We print all the keys and values of data to the console.

Free Resources