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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With