Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Looping through an object in JavaScript

There's a pretty standard way to manipulate an array and return the slightly transformed contents using .map(), but there's a lot of options when it comes to objects, opening the door to potential confusion. Here's an approach to looping through an object in JS

Let's start with the following object:

let authors = {
    "Kyle": {"description": "Likes Cats"},
    "Brian": {"description": "Automation champion"},
    "Sandra": {"description": "Swiss army knife"}
}

Iterating with for...in

For...in will only give you the key used to identify each property, so you'll have to use that key to lookup the actual value itself

for (let key in authors) {
    let value = authors[key]
    console.log(key, value)
}

Which will yield:

// "Kyle", {"description": "Likes Cats"}
// "Brian", {"description": "Automation champion"}
// "Sandra", {"description": "Swiss army knife"}

Iterating with for...of & Object.entries

Object.entries converts an object's enumerable properties and their values to an array of arrays containing [key, value] items

So Object.entries(authors) will produce the following array:

[
  ["Kyle", {"description": "Likes Cats"}],
  ["Brian", {"description": "Automation champion"}],
  ["Sandra",  {"description": "Swiss army knife"}]
]

Combining that with the for...of operator, we can loop through the object like this:

for (let [key, value] of Object.entries(authors)) {
    console.log(key, value)
}

Which yields the same results as before

// "Kyle", {"description": "Likes Cats"}
// "Brian", {"description": "Automation champion"}
// "Sandra", {"description": "Swiss army knife"}

Difference between for...of and for...in

According to MDN:

Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over.

The for...in statement iterates over the enumerable properties of an object, in an arbitrary order.

The for...of statement iterates over an iterable object's values defines to be iterated over.

TypeError: 'x' is not iterable

If you try to loop over an object directy with for...of, you'll get the message:

TypeError authors is not iterable

As with the following code:

for (let key of authors) {
    console.log(key)
}

The issue is there's a difference between a plain old object and an iterable object. This can be solved by wrapping authors in Object.keys, Object.entries or any other iterator

Further Reading:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.