5

this code below works well but the ESLint plugin show the warning:"Using 'ForinStatement' is not allowed" so i want to change it to other ways to prevent the warning message:

    let count = 0;
    for (const key in groups) {
      if (Object.prototype.toString.call(groups[key]) === '[object Object]') {
        if ({}.hasOwnProperty.call(groups[key], 'users')) {
          count += groups[key].users.length;
        }
      }
    }
methis
  • 411
  • 1
  • 5
  • 16

4 Answers4

14

If your goal alone is to avoid errors in your ESLint, i'd suggest using Object.keys(obj).forEach() I usually go with this approach in my own projects.

Pseudo-example:

Object.keys(groups).forEach(key => {
    if (Object.prototype.toString.call(groups[key]) === '[object Object]') {
        if ({}.hasOwnProperty.call(groups[key], 'users')) {
            count += groups[key].users.length;
        }
    }
});
roberrrt-s
  • 7,249
  • 2
  • 41
  • 53
  • 2
    thank, it work perfectly. However to prevent ESLint, you should change "Object.keys(groups).forEach(key => {" to "Object.keys(groups).forEach((key) => {" – methis Nov 02 '16 at 03:18
  • Arrow scoped parameters do not require parenthesis when single: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions It's neater to do it your way though, ++! – roberrrt-s Nov 02 '16 at 07:34
1

Here are three possible ways of solving this depending on what part of the map you need, the keys, the values or both the key/value pairs.

If you need not only the key, but the value in the map you might choose:

for (const [key, value] of Object.entries(object)) {
  // ...
}

If you only need the keys:

for (const key of Object.keys(object)) {
  // ...
}

Finally, if you only need the values, but not the keys you can use:

for (const value of Object.values(object)) {
  // ...
}
nycynik
  • 6,712
  • 5
  • 54
  • 80
Simon Zyx
  • 4,538
  • 1
  • 21
  • 34
0

You use a single line for checking and counting.

let count = Object.keys(groups).reduce((r, key) =>
    r + (('users' in groups[key]) && groups[key].users.length || 0), 0);
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
  • Btw, you better use `'users' in groups[key]` (instead of `groups[key].hasOwnProperty('users')`) since otherwise semantics of the code is different. – zerkms Nov 01 '16 at 09:50
0

I like to implement an it helper function to iterate objects:

function* it(obj) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      yield [key, obj[key]];
    }
  }
}

Then you can iterate like so:

for (const [key, value] of it(obj)) {
  if ({}.toString.call(value) === '[object Object]' &&
      value.hasOwnProperty('users')) {
      count += connections[key].users.length;
    }
}

While this method still uses for..in, it's now contained in one function, and you can make a single exception in your ESLint file for it. Then you don't need to use it ever again.

Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292