Iterating Through JavaScript Objects: A Guide with Examples


In JavaScript, objects can be iterated through using several methods, including the for-in loop, Object.keys(), Object.values(),and Object.entries().

Example 1: Using the for-in loop

const user = {
    name: "Tiya",
    age: 30,
    job: "Programmer"
};

for (let key in user) {
    console.log(`${key}: ${user[key]}`);
}
Output
name: Tiya
age: 30
job: Programmer

Example 2: Using Object.keys()

const user = {
    name: "Tiya",
    age: 30,
    job: "Programmer"
};

const keys = Object.keys(user);
keys.forEach(key => {
    console.log(`${key}: ${user[key]}`);
});

Output
name: Tiya
age: 30
job: Programmer

Example 3: Using Object.values()

const user = {
    name: "Tiya",
    age: 30,
    job: "Programmer"
};

const values = Object.values(user);
values.forEach(value => {
    console.log(value);
});
Output
Tiya
30
Programmer

Example 4: Using Object.entries()

const user = {
    name: "Tiya",
    age: 30,
    job: "Programmer"
};

const entries = Object.entries(user);
entries.forEach(entry => {
    console.log(`${entry[0]}: ${entry[1]}`);
});
Output
name: Tiya
age: 30
job: Programmer

we can use many different ways to iterate through JavaScript objects using a for loop.iterate through an object is using the Object.keys() method. This method returns an array of the object's own property names. Here is an example:

const person = {
    name: "Tiya",
    age: 30,
    job: "Programmer"
};

const keys = Object.keys(person);
for (let i = 0; i<keys.length; i++) {
    console.log(keys[i] + ": " + person[keys[i]]);
}

In this example, we are using the Object.keys() method to get an array of the object's own property names. We can then use a traditional for loop to iterate through the array.

Output
name: Tiya
age: 30
job: Programmer

Lastly, we can use the Object.entries() method to iterate through an object. This method returns an array of arrays, where each inner array is a key-value pair of the object's properties. Here is an example:

const person = {
    name: "Tiya",
    age: 30,
    job: "Programmer"
};

const entries = Object.entries(person);
for (let i = 0; i<entries.length; i++) {
    console.log(entries[i][0] + ": " + entries[i][1]);
}

In this example, we are using the Object.entries() method to get an array of arrays, where each inner array is a key-value pair of the object's properties. We can then use a traditional for loop to iterate through the array.

Output
name: Tiya
age: 30
job: Programmer

In conclusion, there are several ways to iterate through JavaScript objects and each method has its own use case. The for-in loop is useful when you need to access both the keys and values of an object, Object.keys() and Object.values() are useful when you only need to access the keys or values respectively, and Object.entries() is useful when you need to access both the keys and values in an iterable format.

List of Programs


JS Practical Questions & Answers


JS Practical Project