1

I have this code:

data.forEach(item => {
    for (const i in Object.keys(item)) {
      const key = Object.keys(item)[i];
      //..
    }
  });

eslint throwing an error:

error The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype guard-for-in

I did research and tried to fix that this way:

data.forEach(item => {
if (pattern.hasOwnProperty(i)) {
    for (const i in Object.keys(item)) {
      const key = Object.keys(item)[i];
      //..
    }
  }
});

So that made the linter happy but the for..in loop now does not work.

that is the value of the item - { 'bla': '42' }

Any ideas how to solve?

frederj
  • 1,483
  • 9
  • 20
Sergino
  • 10,128
  • 30
  • 98
  • 159
  • 1
    Never use [for...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in), use [for ... of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of), or use `.forEach` because that's kind of what it's for (`for ... in` is a legacy construct that does all kinds of things you really don't want). And there is _no_ need to double iterate, the top level iteration already does exactly what you want: `for (const [key, value] of Object.entries(items)) { ... }` or `Object.entries(items).forEach(([key, value]) => {... });` and off you go. – Mike 'Pomax' Kamermans Sep 22 '21 at 00:06
  • @Mike'Pomax'Kamermans great, it seems more like an answer, not a comment ;) – Sergino Sep 22 '21 at 00:12
  • Oh, no, this is _absolutely_ a comment. No one familiar with iterating over lists would write a double-nested loop on the _same_ list =) – Mike 'Pomax' Kamermans Sep 22 '21 at 00:13

1 Answers1

2

It should be either

for (const key of Object.keys(item)) {
  …
}

or

Object.keys(item).forEach(key => {
  …
});

or

for (const key in item) {
  …
}

but not a mix of for … in with Object.keys. Also no, it should not be necessary to wrap loop bodies in if statements, better disable that linter rule (and rather enable no-prototype-builtins, which would've caught your broken fix).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375