Explain Codes LogoExplain Codes Logo

How do I loop through or enumerate a JavaScript object?

javascript
promises
callbacks
functions
Alex KataevbyAlex Kataev·Feb 12, 2025
TLDR

To enumerate properties in a JavaScript object, use the for...in loop:

const obj = { a: 1, b: 2, c: 3 }; for (const key in obj) { // Check "if key has key!" Hmm, grammar, eh? if (obj.hasOwnProperty(key)) { console.log(`${key}: ${obj[key]}`); } }

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:

const obj = { a: 'Hello', b: 'Stack', c: 'Overflow' }; // "A key to success: Find keys!" for (const key of Object.keys(obj)) { console.log(`${key}: ${obj[key]}`); } // "Values are not just numbers anymore!" for (const value of Object.values(obj)) { console.log(value); } // "It takes two to make a thing go right: [key, value]!" for (const [key, value] of Object.entries(obj)) { console.log(`${key}: ${value}`); }

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:

const symbolKey = Symbol('unique'); const newObj = { [symbolKey]: 'symbolValue', hidden: 'invisible' }; Object.defineProperty(newObj, 'hidden', { enumerable: false }); // "Symbol hunting season is open!" console.log(Object.getOwnPropertySymbols(newObj)); // Output: [Symbol(unique)] console.log(Object.getOwnPropertyNames(newObj)); // Output= ['hidden']

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:

// "Lo-Dash: An underscore on steroids!" _.forEach(discoBall, (value, key) => { console.log(key + ' Disco ' + value); }); // Are you my own property or an imposter? Check with _.forOwn _.forOwn(discoBall, (value, key) => { console.log('Retro ' + key + ': ' + value); });

Remember, utility libraries are like cheat codes. They can handle edge cases and weird data types with ease.