DEV Community

loading...

Looping through objects in JavaScript

zellwk profile image Zell Liew 🤗 Originally published at zellwk.com Updated on ・2 min read

Once in a while, you may need to loop through Objects in JavaScript. The only way to do so before ES6 is with a for...in loop.

The problem with a for...in loop is that it iterates through properties in the Prototype chain. When you loop through an object with the for...in loop, you need to check if the property belongs to the object. You can do this with hasOwnProperty.

for (var property in object) {
  if (object.hasOwnProperty(property)) {
    // Do things here
  }
}
Enter fullscreen mode Exit fullscreen mode

We no longer have to rely on for...in and hasOwnProperty now. There's a better way.

A better way to loop through objects

The better way to loop through objects is first to convert the object into an array. Then, you loop through the array.

You can convert an object into an array with three methods:

  1. Object.keys
  2. Object.values
  3. Object.entries

Object.keys

Object.keys creates an array that contains the properties of an object. Here's an example.

const fruits = {
  apple: 28,
  orange: 17,
  pear: 54,
}

const keys = Object.keys(fruits)
console.log(keys) // [apple, orange, pear]
Enter fullscreen mode Exit fullscreen mode

Object.values

Object.values creates an array that contains the values of every property in an object. Here's an example:

const fruits = {
  apple: 28,
  orange: 17,
  pear: 54,
}

const values = Object.values(fruits)
console.log(values) // [28, 17, 54]
Enter fullscreen mode Exit fullscreen mode

Object.entries

Object.entries creates an array of arrays. Each inner array has two item. The first item is the property; the second item is the value.

Here's an example:

const fruits = {
  apple: 28,
  orange: 17,
  pear: 54,
}

const entries = Object.entries(fruits)
console.log(entries)
// [
//   [apple, 28],
//   [orange, 17],
//   [pear, 54]
// ]
Enter fullscreen mode Exit fullscreen mode

My favorite of the three is Object.entries because you get both the key and property values.

Looping through the array

Once you've converted the object into an array with Object.keys, Object.values, or Object.entries, you can loop through it as if it was a normal array.

// Looping through arrays created from Object.keys
const keys = Object.keys(fruits)
for (const key of keys) {
  console.log(key)
}

// Results:
// apple
// orange
// pear
Enter fullscreen mode Exit fullscreen mode

If you use Object.entries you might want to destructure the array into its key and property.

for (const [fruit, count] of entries) {
  console.log(`There are ${count} ${fruit}s`)
}

// Result
// There are 28 apples
// There are 17 oranges
// There are 54 pears
Enter fullscreen mode Exit fullscreen mode

Wrapping up

The better way to loop through objects is first convert it into an array with one of these three methods.

  1. Object.keys
  2. Object.values
  3. Object.entries

Then, you loop through the results like a normal array.

If this lesson has helped you, might enjoy Learn JavaScript, where you'll learn how to build anything you want from scratch. Enrollment for Learn JavaScript opens in July 2018 (in two weeks!).


Thanks for reading. This article was originally posted on my blog. Sign up for my newsletter if you want more articles to help you become a better frontend developer

Discussion (7)

pic
Editor guide
Collapse
paulooze profile image
Pavol Porubský

While I generally agree with the message here (using Object.keys(), Object.values() and Object.entries()), I wouldn't generally recommend using for of loop (or any for loop for that matter). It doesn't work well with immutable data. Using pure functions like Array.map(), Array.forEach() or Array.filter() is generally better idea - you don't have to deal with side effects and it's generally easier to read.

Collapse
kepta profile image
Kushan Joshi • Edited

I totally agree with you regarding for loop and how .map, .reduce, .filter are a heavenly match for functional programming. But there are cases where I feel for of loop is a natural fit:

  • Iterator: Javascript now has native support for iterators (I talk about them in my article), so dealing with Map, Set, Array etc, the for of loop becomes a natural choice over converting these iterators to arrays and then applying the functional methods.

  • Async: Another area I find for of loop a rather easier read is when I have to iterate through an async collection. I talk about some examples of async for loop here.

Collapse
tunaxor profile image
Angel D. Munoz

it's generally easier to read.

I'd say this has more to do with your style, while I prefer these methods also, I've seen bunch of colleagues not understanding how these methods flow
it feels magical to them, they rather have a for-of (or a good old for) perhaps because my colleagues do tend to do more procedural stuff but y' know what works best for you is the way to go most of the time

but to reasure, I do prefer to use map, forEach, filter, and reduce when possible

Collapse
kepta profile image
Kushan Joshi • Edited

Zell Liew, just wanted to add my 2cents to this well written article.

I feel if one realises that a particular object would require a lot of iteration then maybe they need to start thinking about ditching the object in favour of data structures which have a first party support for iteration.

With ES6 we have a new fancy data structure called Map and it is a perfect fit for those cases where you are overloading an object with thousands of properties and also want to iterate through them.

A simple example of Map.

var map = new Map();

map.set('random', 34);
map.set('abc', 42);

for(const val of map.values()) {
   console.log(val);
}

MDN Docs for Map

Collapse
zellwk profile image
Zell Liew 🤗 Author

Thanks for adding on!

Collapse
ezrafree profile image
ezrafree

Under the "Looping through the array" section, in the first code example, you have:

console.log(keys)

This should be key, not keys:

console.log(key)
Collapse
lmbarr profile image
Luis Miguel

Nice and concise...very helpful thank you