How to Loop Through Properties of an Object in JavaScript

How to Loop Through Properties of an Object in JavaScript

Ferenc Almasi β€’ 2020 August 12 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

Easily loop through the properties of an object without including inherited ones with the help of the hasOwnProperty method:

Copied to clipboard! Playground
// Loop through object properties without including
// inherited properties

const object = { ... };

for (const key in object) {
    if (object.hasOwnProperty(key)) {
        // work on properties
    }
}
loop.js

As you can see, for the for statement, the in keyword is used. However, we also have an if statement that checks for hasOwnProperty. This is because the in keyword also includes inherited properties. To filter them out, we need the if statement.


For a simpler solution, you can also use Object.keys with a forEach combined:

Copied to clipboard!
Object.keys(object).forEach((key, index) => {
    console.log(`key: ${key}, value: ${object[key]}, index: ${index}`);
});
object.keys.js

It has a fairly good global support, also supported in IE down to version 9.

How to Loop Through Properties of an Object in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.