Algorithm


  1. Initialize Object:

    • Create an object to iterate through.
  2. Get Object Keys:

    • Retrieve the keys of the object using Object.keys(obj) method.
  3. Iterate Through Keys:

    • Use a loop (for loop or forEach) to iterate through the keys obtained in the previous step.
  4. Access Object Properties:

    • Inside the loop, access each property of the object using the current key.
  5. 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

x
+
cmd
name - John
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

x
+
cmd
name - John
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

x
+
cmd
name - John
age - 20
hobbies - ["reading", "games", "coding"]
Advertisements

Demonstration


JavaScript Programing to Loop Through an Object-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way