Algorithm
-
Initialize Object:
- Create an object to iterate through.
-
Get Object Keys:
- Retrieve the keys of the object using
Object.keys(obj)
method.
- Retrieve the keys of the object using
-
Iterate Through Keys:
- Use a loop (for loop or forEach) to iterate through the keys obtained in the previous step.
-
Access Object Properties:
- Inside the loop, access each property of the object using the current key.
-
Perform Desired Operations:
- Perform any desired operations or actions with the property values.
Code Examples
#1 Code Example- Loop Through Object Using for...in
Code -
Javascript Programming
// program to loop through an object using for...in loop
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
// using for...in
for (let key in student) {
let value;
// get the value
value = student[key];
console.log(key + " - " + value);
}
Copy The Code &
Try With Live Editor
Output
name - John
age - 20
hobbies - ["reading", "games", "coding"]
age - 20
hobbies - ["reading", "games", "coding"]
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
const person = {
gender: 'male'
}
// inheriting property
student.__proto__ = person;
for (let key in student) {
let value;
// get the value
value = student[key];
console.log(key + " - " + value);
}
Copy The Code &
Try With Live Editor
Output
name - John
age - 20
hobbies - ["reading", "games", "coding"]
gender - male
age - 20
hobbies - ["reading", "games", "coding"]
gender - male
#3 Code Example- Loop Through Object Using Object.entries and for...of
Code -
Javascript Programming
// program to loop through an object using for...in loop
const student = {
name: 'John',
age: 20,
hobbies: ['reading', 'games', 'coding'],
};
// using Object.entries
// using for...of loop
for (let [key, value] of Object.entries(student)) {
console.log(key + " - " + value);
}
Copy The Code &
Try With Live Editor
Output
name - John
age - 20
hobbies - ["reading", "games", "coding"]
age - 20
hobbies - ["reading", "games", "coding"]
Demonstration
JavaScript Programing to Loop Through an Object-DevsEnv