Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Object.forOwn loop over object keys functionality [duplicate]

Disclaimer: I'm aware there are similar questions, but none convinced me it was the final solution.


I'm very surprised to find out there doesn't seem to be a standard way to functionally loop over an object.

Lodash has _.forOwn().

The ES6 way seems to be:

Object.keys(object).forEach(key => { console.log(key, object[key]); });

but this is not functional since object is external of the iterator function.

I haven't even found any polyfill.

for ... in doesn't even seem like a solution to me.

How do you guys write this?

like image 868
Augustin Riedinger Avatar asked Jun 19 '26 00:06

Augustin Riedinger


1 Answers

ES2017 introduces Object.entries() method, which appears to be what you're looking for:

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

That was already mentioned in this answer.

Note that you can also use a Map instead of plain object—it has a forEach() method.

like image 167
Michał Perłakowski Avatar answered Jun 20 '26 14:06

Michał Perłakowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!