Is there a built-in way to loop through the properties of an object?
Discover the object's own properties by using for...in
along with Object.hasOwnProperty
:
This way we are ensuring we're logging only the object's direct properties, leaving out the inherited ones.
Beyond the basics: Enhancing object iteration
Let's move beyond mere loops and extend our paths in the vast universe of JavaScript object iteration.
Handling object properties with ES6 methods
Object.keys()
, Object.values()
, and Object.entries()
: The three Musketeers of JavaScript keys, values, and both together:
These methods are your friends in the realm of array iterators. They pave the way for .forEach()
, .map()
, .filter()
, and more to bring forth powerful ways to remodel object data.
ES6: For better for-loop
The for...of
loop coupled with Object.entries()
is your dynamic duo to iterate over keys and values with ease:
Framework-specific enchants
In a Handlebars.js world, objects can be accessed using the tools {{#each}}
, {{@key}}
, and {{this}}
:
The Joneses of Handlebars.js can even use their own custom helpers for complex situations. They perform feats such as looping through and showing property-value pairs:
Not to be left behind, Ember.js features Ember.Handlebars.registerHelper
to create similar helpers, combining it with Ember.get
for safe object property access.
Beware the prototype
Be heedful of the hasOwnProperty
method when iterating. It acts as a gatekeeper for properties that arrived from the object's prototype. Use it wisely to filter the intrinsic properties:
This way, you even guard against that one strange property named "hasOwnProperty.” You heard it here first!
Taking into account enumerable properties
Remember! Not all properties like to socialize. Some are non-enumerable. Fear not, Object.keys()
will only return enumerable properties for you. But if you're into social inclusivity, Object.getOwnPropertyNames()
will include even the introverts.
Was this article helpful?