Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid for...in eslint issues?

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?

like image 870
user7496931 Avatar asked Aug 29 '18 20:08

user7496931


1 Answers

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
});
like image 79
Nicholas Tower Avatar answered Oct 20 '22 13:10

Nicholas Tower