Mark As Completed Discussion

When working with objects in JavaScript, it is often necessary to iterate over their properties to perform certain operations or access specific data. Thankfully, JavaScript provides us with several techniques for iterating over object properties.

One common method is to use a for...in loop. This loop iterates over each key in an object and allows us to access the corresponding value.

Here's an example of using a for...in loop to iterate over the properties of an object:

JAVASCRIPT
1const student = {
2  name: 'John',
3  age: 25,
4  country: 'USA'
5};
6
7for (let key in student) {
8  console.log(key + ': ' + student[key]);
9}

In this example, the loop iterates over each key in the student object (name, age, country) and logs both the key and the corresponding value.

Another technique is to use the Object.keys() method. This method returns an array of all the keys in an object, which we can then iterate over using methods like forEach() or a traditional for loop.

Here's an example of using Object.keys() and forEach() to iterate over the properties of an object:

JAVASCRIPT
1const student = {
2  name: 'John',
3  age: 25,
4  country: 'USA'
5};
6
7Object.keys(student).forEach(key => {
8  console.log(key + ': ' + student[key]);
9});

In this example, Object.keys(student) returns an array of keys (name, age, country), and forEach() is used to iterate over the array and log both the key and the corresponding value.

Lastly, we can use the Object.entries() method to get an array of key-value pairs for each property in an object. We can then iterate over the array using methods like forEach() or destructuring to access the key-value pairs separately.

Here's an example of using Object.entries() and destructuring to iterate over the properties of an object:

JAVASCRIPT
1const student = {
2  name: 'John',
3  age: 25,
4  country: 'USA'
5};
6
7Object.entries(student).forEach(([key, value]) => {
8  console.log(key + ': ' + value);
9});

In this example, Object.entries(student) returns an array of key-value pairs (name: 'John', age: 25, country: 'USA'), and destructuring is used to access the key and value separately within the forEach() callback.

Iterating over object properties is a powerful technique that allows us to perform various operations on objects. Depending on your needs, you can choose the method that best suits your use case!

Try running the code examples to see the output.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment