How do I loop through or enumerate a JavaScript object?
⚡TLDR
To enumerate properties in a JavaScript object, use the for...in loop:
Be sure to use obj.hasOwnProperty(key) to skip inherited properties and ensure you're only focusing on the object's unique properties.
Taking things up a notch: Cleaner iteration methods
Embrace the power of Object.keys(), Object.values(), and Object.entries()
For cleaner and more manageable code, utilize these modern JavaScript methods. They make enumeration a breeze:
Hunting for elusive Symbols and non-enumerable properties
Symbols and non-enumerable properties - they won't show up in your usual for...in loop or Object.keys(). Here's how to catch them:
Library to the rescue: Lo-Dash and Underscore.js
Feel like for...in is too mainstream? Shake things up with utility libraries like Lo-Dash or Underscore.js:
Remember, utility libraries are like cheat codes. They can handle edge cases and weird data types with ease.
Linked
Was this article helpful?