How to iterate (keys, values) in JavaScript?
Iterate keys and values with Object.entries()
, applying a for...of
loop on the result.
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.
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.
ES5 also brought us Object.keys()
, which, once combined with forEach
, gave us a nifty way to loop over an object's keys.
Mapping through: Map objects
Now let's talk about Map()
objects. A Map()
holds key-value pairs and remembers the order of entries.
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.
Was this article helpful?