how to loop object javascript
How to Loop Object in JavaScript?
Looping through objects in JavaScript is a common task that you will come across in your coding journey. In this article, we will explore different ways to loop through objects in JavaScript.
Method 1: for...in loop
The for...in loop is the most commonly used method to loop through objects in JavaScript. It allows you to iterate over all the enumerable properties of an object. Here is an example of how to use the for...in loop:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output:
firstName: John
lastName: Doe
age: 30
Method 2: Object.keys() method
The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop. We can then use this array to loop through the object. Here is an example of how to use the Object.keys() method:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
const keys = Object.keys(person);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
console.log(key + ": " + person[key]);
}
Output:
firstName: John
lastName: Doe
age: 30
Method 3: Object.values() method
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as we get with a normal loop. We can then use this array to loop through the object. Here is an example of how to use the Object.values() method:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
const values = Object.values(person);
for (let i = 0; i < values.length; i++) {
console.log(values[i]);
}
Output:
John
Doe
30
Method 4: Object.entries() method
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as we get with a normal loop. We can then use this array to loop through the object. Here is an example of how to use the Object.entries() method:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
const entries = Object.entries(person);
for (let key in entries) {
console.log(entries[key][0] + ": " + entries[key][1]);
}
Output:
firstName: John
lastName: Doe
age: 30
These are the four most commonly used methods to loop through objects in JavaScript. Choose whichever method suits your needs and enjoy coding!