I have an object with some keys and values.
I initially had this loop:
for(const key in commands) {
if (commands.hasOwnProperty(key)) {
const value = commands[key];
// Do something else
}
}
That gave me the following eslint error:
for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array. (no-restricted-syntax)
So I changed it to this:
Object.keys(commands).forEach(key => {
if (commands.hasOwnProperty(key)) {
const value = commands[key];
}
});
Now, I'm getting the following error due to hasOwnProperty
:
Do not access Object.prototype method 'hasOwnProperty' from target object. (no-prototype-builtins)
How can I write a simple loop that iterates over the keys whilst avoiding eslint errors?
When using Object.keys
, you do not need to check hasOwnProperty
. Object.keys produces an array of exclusively own properties. This is why the first eslint error was recommending that you use it.
For the second lint error, it's recommending that you do
Object.prototype.hasOwnProperty.call(commands, key)
The reason this lint rule exists is that it's possible for commands.hasOwnProperty
to be undefined
, if commands was created using Object.create(null)
. In your case though, you just need to delete the check:
Object.keys(commands).forEach(key => {
const value = commands[key];
// Do something else
});
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