Categories
JavaScript Answers

How to traverse through JavaScript object properties?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *