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:
Object.entries()
returns an array (with numeric indices) of key-value pairs.- Using
for ... of
we loop all those pairs. - Thanks Array Destructuring we can assign easily assign both the key and value into the
key
andvalue
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.
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!