methis
methis

Reputation: 471

Other ways to loop through a JavaScript object?

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;
        }
      }
    }

Upvotes: 5

Views: 7924

Answers (4)

Simon Zyx
Simon Zyx

Reputation: 7181

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)) {
  // ...
}

Upvotes: 3

roberrrt-s
roberrrt-s

Reputation: 8210

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;
        }
    }
});

Upvotes: 15

Nina Scholz
Nina Scholz

Reputation: 386746

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);

Upvotes: 0

Madara's Ghost
Madara's Ghost

Reputation: 175038

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.

Upvotes: 0

Related Questions