47

This is my original code:

const buildTableContent = (settings) => {
  const entries = [];
  for (const key in settings) {
    for (const subkey in env[key]) {

settings is basically a dictionary of dictionary

  {  
    'env': {'name': 'prod'}, 
    'sass: {'app-id': 'a123445', 'app-key': 'xxyyzz'}
  }

It triggered the following AirBnb style guide error:

35:3 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 change the code to

const buildTableContent = (settings) => {
  const entries = [];
  for (const key of Object.keys(settings)) {
    for (const subkey of Object.keys(env[key])) {

as suggested.

Now when I run lint, I got this:

35:3 error iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations no-restricted-syntax

So it looks to me either way they are violating some lint style.

How can I fix this issue?

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304

1 Answers1

67

You'd want to use

Object.keys(settings).forEach(key => {
  Object.keys(env[key]).forEach(subkey => {

or potentially Object.entries or Object.values depending on if you actually want the keys.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 2
    I am using redux-saga where I have to sequentially call api using the yield keyword..yield cannot be used in the function callback for forEach since the callback is not a generator function.So I am stuck with the two errors mentioned in the question. Is there a way out ? – anuragb26 Jun 21 '19 at 11:06
  • @anuragb26 Which rule? I'd probably just turn it off. – loganfsmyth Jun 21 '19 at 18:36
  • 4
    'no-restricted-syntax': ...Yeah , i turned it off – anuragb26 Jun 22 '19 at 01:32
  • @anuragb26 in order to use yield you may do something like this for (const elem of elemArray){ yield fn() } – Shubham Kakkar Dec 13 '20 at 08:25
  • 12
    why using forEach is preferred? – Hojat Modaresi Jan 09 '21 at 11:39
  • @HojatModaresi I don't think it is preferred, but this question was explicitly about what to do when ESLint rules are in place to disallow it. If you want to use `for...of` then don't use the lint rules the OP is using. – loganfsmyth Jan 09 '21 at 20:46