Explain Codes LogoExplain Codes Logo

Iterate through object properties

javascript
object-iteration
destructuring
modern-js
Nikita BarsukovbyNikita BarsukovยทAug 5, 2024
โšกTLDR

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:

const obj = { a: 1, b: 2, c: 3 }; for (const prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { // Code runs faster when it gets a laugh or two ๐Ÿ˜† console.log(`Property "${prop}" found! Dealing with value: ${obj[prop]}`); } }

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

Object.keys(obj).forEach(key => { console.log(`Using Object.keys to find "${key}". Let's see what it hides: ${obj[key]}`); });

Use Object.entries to harvest key-value pairs

Object.entries(obj).forEach(([key, value]) => { console.log(`Hey ${key}, what's up? Oh, it's ${value}!`); });

Using destructuring for graceful and concise iteration

Sometimes, you just have to show off a bit. That's where destructuring shines!

for (const [key, value] of Object.entries(obj)) { console.log(`Property "${key}" has a secret: ${value}. But don't tell anyone ๐Ÿ˜‰`); }

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.

for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { console.log(`Confirmed "${key}" is ours! Now, what secret does it hold: ${obj[key]}?`); } }

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.

Object.values(obj).forEach(value => { console.log(`Shhhh... The value is: ${value}`); });

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.

for (const [key, value] of Object.entries(obj)) { console.log(`If "${key}" is the question, then ${value} is the answer!โœŒ๏ธ`); }