Skip to content
Advertisement

Lint issue with for loop

The following logic works as intended. I have no means to change the lint rules.
data in this case is just an Object such as follows which gets passed in.

const testData = {
  item_one: 'item',
};

This is the function which takes in above data

const convert = (data) => {
  for (const key in data) {
      // ...
  }
  return data;
};

Getting lint errors as follows for my for loop as follows:

  1. 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
  2. The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype

To address point one, tried to switch the loop to be of type foreach as follows and that resolves the lint.
But that has broken my logic for some reason… Bit frustrating for logic to break due to lint.

data.forEach((previousKey) => {
    // ... same logic as above inside that loop loop
}

For point 2, I do want to iterate over every property. How could I resolve this lint error?

Please advice. Thank you.

Advertisement

Answer

Only arrays have a forEach method; data.forEach won’t work, since data isn’t an array. You need this

data.forEach((previousKey) => {

to be

Object.keys(data).forEach((previousKey) => {

or, if you want the associated value too

Object.entries(data).forEach(([previousKey, value]) => {

For point 2, I do want to iterate over every property.

I don’t think you deliberately want to iterate over inherited properties as well. Do you really have properties on internal prototypes, eg

const obj = Object.create({ foo: 'bar' });
obj.someProp = 'someVal';

, and you’d want to iterate over both foo and someProp?

That sounds quite unusual – possible, but very weird. That’s why the linter is warning you against using for..in. If you do need to iterate over inherited properties, either disable the linter rule for this one line (preferable, since that’ll make the code easiest), or (much more verbosely) iterate over the own-properties of the instance object with Object.keys, then do the same for the instance’s prototype, and so on, until you reach the end of the prototype chain.

Advertisement