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
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

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.