ES6/ES2015: Looping over an Object with keys and values

javascript-logo-banner

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.
    object-entries
  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}`);
});
Elsewhere ,

Leave a Reply

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.