Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        }
      }
    }
like image 574
methis Avatar asked Nov 01 '16 09:11

methis


People also ask

How many ways can you iterate objects in JavaScript?

There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.

Can you loop through properties of an object JavaScript?

Object. entries() is the recommended method for iterating over an object's properties in JavaScript. Since the method returns a multidimensional array, we can greatly simplify our code by using the array destructuring syntax to retrieve each property into a separate variable.


2 Answers

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;
        }
    }
});
like image 149
roberrrt-s Avatar answered Dec 01 '22 01:12

roberrrt-s


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)) {
  // ...
}
like image 27
Simon Zyx Avatar answered Dec 01 '22 00:12

Simon Zyx