How to Loop Through Properties of an Object in 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
}
}
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}`);
});
It has a fairly good global support, also supported in IE down to version 9.
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews