The closest equivalent is looping over Object.keys()
with forEach()
:
Object.keys(keyCodeByName).forEach(keyCodeName => {
// something happens
});
This is actually roughly equivalent to the following loop:
for (let keyCodeName in keyCodeByName) {
if (keyCodeByName.hasOwnProperty(keyCodeName)) {
// something happens
}
}
because Object.keys()
only returns own properties, while for-in
will process inherited properties as well.
Many programmers forget to do the hasOwnProperty()
check, and in most cases it's innocuous because none of the inherited properties are enumerable. So if the code you're trying to convert doesn't have the check, it's more likely that they didn't realize they needed it, not that they really want to process inherited properties. So using Object.keys()
is likely to be closer to the intended behavior.
See When do I need to use hasOwnProperty()?