Iterate through object properties
In JavaScript, use the for...in
loop to iterate over an object's properties. Always use the Object.prototype.hasOwnProperty.call
function to screen for the object's own properties to exclude those inherited. An easy-to-follow example is shown below:
Outputs:
Property "a" found! Dealing with value: 1
Property "b" found! Dealing with value: 2
Property "c" found! Dealing with value: 3
Please note that for...in
loops over all enumerable property names. Using hasOwnProperty
ensures we only interact with the object's own properties and not any sneaky inherited ones.
Using modern JavaScript features for object property iteration
The simple for...in
loop described earlier gets the job done, but modern JavaScript provides us with more elegant, fool-proof methods that are worth exploring!
Use Object.keys
to harvest property names
Use Object.entries
to harvest key-value pairs
Using destructuring for graceful and concise iteration
Sometimes, you just have to show off a bit. That's where destructuring shines!
Always verify property ownership while iterating
When dealing with complex objects, we might encounter properties that we'd rather not iterate over, such as those inherited through the prototype chain.
Iterate over just the values
There will be times when we're only interested in the values. Object.values
is just the tool for such situations.
Embrace modern JavaScript with Object.entries
The Object.entries
function provides an easy to understand interface for naviagting key-value pairs. With destructuring, it's a trip down EasyToUnderstand Lane.
Was this article helpful?