For..in loops in JavaScript - key value pairs
For those of you in a hurry, here's a quick snippet that shows you how to access key-value pairs in JavaScript objects, using a **for...in**
loop and a **hasOwnProperty**
check 101:
This way you're owning it, iterating only over the object's specific properties, not the ones it borrowed from its well-meaning prototype.
The many faces of iteration, and when to use them
Different tasks, different environments, but same need for iteration. Here are few ways to meet that need with style:
ES6: for..of with Object.entries
for..of
with Object.entries
is like the hot new couple on the JavaScript block (hey, it's ES6 town here!). Let's introduce them to our object:
Your gateway to array methods: Object.keys
Want to use your favourite array methods, but stuck with an object? Object.keys
is your ticket to a functional programming party:
The Unlockers: Object.values and Object.entries
Unleash the power of arrays on your object with Object.values
and Object.entries
.
Beware the quirks: best practices and common pitfalls
Every JavaScript veteran knows that for...in
demands respect. It has rules, and expectations, sometimes bordering on quirks. But hey, don't we all?
HasOwnProperty: check your lineage
While iterating with for..in
, you don't want to accidentally take some prototypes properties. So ask every property: "do you really belong here?"
ES6's got you covered
Ever since Object.entries
swiped right on JavaScript, it has been the preferred choice over for...in
, notably for avoiding prototype chain issues.
Was this article helpful?