ES6 ES2015: Looping over an Object with keys and values


Say you have an object like this:

const obj = {
    firstName: 'John',
    lastName: 'Doe',
    age: 50,
    eyeColor: 'blue'

Using lodash’s forEach you can easily loop over this object, with easy access to both the key and the value:

_.forEach(obj, function(value, key) {
    console.log(key + ' ' + value);

But what about ES2015? After fiddling a bit, I came to the conclusion that a simple one-liner is all it takes to loop over it:

for (const [key, value] of Object.entries(obj)) {
    console.log(`${key}: ${value}`);

The output will be this:

firstName: John
lastName: Doe
age: 50
eyeColor: blue

In case you were wondering, here’s how it works:

  1. Object.entries() returns an array (with numeric indices) of key-value pairs.
  2. Using for ... of we loop all those pairs.
  3. Thanks Array Destructuring we can assign easily assign both the key and value into the key and value variables.

Alternatively you can also get the same result using Array#forEach(), which might be more readable to you (and has a closer resemblance to _.forEach):

Object.entries(obj).forEach((entry) => {
    const [key, value] = entry;
    console.log(`${key}: ${value}`);

You can make this even more condense by destructuring directly in the function:

Object.entries(obj).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);

💻 The examples embedded in this post are part of a talk on ESNext named “What’s next
 for JavaScript?”, which I gave at a Fronteers België meetup and Frontend United 2018 (Utrecht). You can check the slides / a recording out here. I’m available for bringing this talk at your meetup/conference.

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Published by Bramus!

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.