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 objectconst data = {name: 'Shubham',designation: 'Software Engineer'}// iterate over objectfor (const obj in data) {// print key and value on consoleconsole.log(`${obj}: ${data[obj]}`)}
Explanation
- Line 2-5: We create an object named
data. - Line 8: We use the
for...inloop to iterate over the properties of the objectdata.
- Line 10: We print all the keys and the values of the object
dataon 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 objectconst data = {name: 'Shubham',designation: 'Software Engineer'}// iterate over objectfor (const [key, value] of Object.entries(data)) {// print key and value on consoleconsole.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 ofdata.
- Line 10: We print all the keys and values of
datato the console.