Explain Codes LogoExplain Codes Logo

How to iterate (keys, values) in JavaScript?

javascript
iterating
object-entries
map-objects
Anton ShumikhinbyAnton Shumikhin·Sep 14, 2024
TLDR

Iterate keys and values with Object.entries(), applying a for...of loop on the result.

const obj = { a: 1, b: 2, c: 3 }; for (const [k, v] of Object.entries(obj)) { console.log(`Key: ${k} Value: ${v}`); }

Outputs each key-value pair, fitting neatly into any use-case.

Let's modernize: ECMAScript 2017

ECMAScript 2017 gave us Object.entries(). This function returns an array of key-value pairs from an object. Perfect for situations where you need to work on both the key and the value.

const user = { name: 'Alice', age: 25 }; Object.entries(user).forEach(([key, value]) => { // Let's spill the tea on Alice console.log(`${key}: ${value}`); }); // Now we know way more about Alice than she'd prefer.

This approach leverages destructuring in the forEach() loop, assigning your object's keys and values to variables for quick and easy use.

Rockin' it old school: Pre-ECMAScript 2015

Before ECMAScript 2015 (ES6), for...in was the iteration workhorse. Just remember to call .hasOwnProperty to ensure you're not inadvertently including inherited properties in your fun.

const oldSchoolObject = { d: 4, e: 5, f: 6 }; for (const key in oldSchoolObject) { if (oldSchoolObject.hasOwnProperty(key)) { // Fetching old school values like it's 1995! console.log(`Key: ${key}, Value: ${oldSchoolObject[key]}`); } }

ES5 also brought us Object.keys(), which, once combined with forEach, gave us a nifty way to loop over an object's keys.

Object.keys(oldSchoolObject).forEach(function(key) { console.log(`Key: ${key}, Value: ${oldSchoolObject[key]}`); }); // Our object just spilled all its secrets. Loose lips sink ships, I say.

Mapping through: Map objects

Now let's talk about Map() objects. A Map() holds key-value pairs and remembers the order of entries.

const myMap = new Map([['x', 10], ['y', 20]]); myMap.forEach((val, key) => { // Talking to maps because we ran out of friends during lockdown. console.log(`Key: ${key}, Value: ${val}`); });

The Map() object also comes with built-in methods like .keys(), .values(), and .entries() for your iterating pleasure.

Let's get practical: Mind the details

Performance and compatibility are two aspects you should consider:

  • Object.entries() creates an array from your object (time-consuming for large objects).
  • for...in is faster but may yield unwanted inherited properties.
  • Map provides consistent iteration order (yay to predictability!).

Get comfortable with these details before choosing your go-to iteration method.