How to traverse through JavaScript object properties?

Sometimes, we want to traverse through JavaScript object properties.

In this article, we’ll look at how to traverse through JavaScript object properties.

How to traverse through JavaScript object properties?

To traverse through JavaScript object properties, we use the for-of loop and the Object.entries property.

For instance, we write

const object1 = {
  a: "somestring",
  b: 42,
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

to call Object.entries to return an array with the key-value pair arrays in object1.

Then we use a for-of loop to get the key and value of each property.

Conclusion

To traverse through JavaScript object properties, we use the for-of loop and the Object.entries property.