Skip to content

Instantly share code, notes, and snippets.

@KyleMit
Created September 3, 2019 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KyleMit/f5527d3d133033c60f7113338a91d425 to your computer and use it in GitHub Desktop.
Save KyleMit/f5527d3d133033c60f7113338a91d425 to your computer and use it in GitHub Desktop.
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"}

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