ChatGPT解决这个技术问题 Extra ChatGPT

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

Lint error message:

src/app/detail/edit/edit.component.ts[111, 5]: for (... in ...) statements must be filtered with an if statement

Code snippet (It is a working code. It is also available at angular.io form validation section):

for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }

Any idea how to fix this lint error?

Maybe accept an answer?

a
akrabi

To explain the actual problem that tslint is pointing out, a quote from the JavaScript documentation of the for...in statement:

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).

So, basically this means you'll get properties you might not expect to get (from the object's prototype chain).

To solve this we need to iterate only over the objects own properties. We can do this in two different ways (as suggested by @Maxxx and @Qwertiy).

First solution

for (const field of Object.keys(this.formErrors)) {
    ...
}

Here we utilize the Object.Keys() method which returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Second solution

for (var field in this.formErrors) {
    if (this.formErrors.hasOwnProperty(field)) {
        ...
    }
}

In this solution we iterate all of the object's properties including those in it's prototype chain but use the Object.prototype.hasOwnProperty() method, which returns a boolean indicating whether the object has the specified property as own (not inherited) property, to filter the inherited properties out.


I'd like to notice that Object.keys is ES5. The only thing from ES6 there is for-of loop. We can iterate array in usual loop from 0 to its length and it would be ES5.
once more notice: if somehow this.formErrors is null, for...in just do nothing, while for ... of Object.keys() would throw error.
i am following the second solution but still i see the lint message. Disabled lint for time being.
Why don't you recommend Object.keys(obj).forEach( key => {...}) ?
@BenCarp - it has serious problems when running in an async function, therefore, at least to me, for ... in/of ... are considered more superior. See: stackoverflow.com/questions/37576685/…
M
Maxxx

A neater way of applying @Helzgate's reply is possibly to replace your 'for .. in' with

for (const field of Object.keys(this.formErrors)) {

This should be the accepted answer as not only it solves the problem, it also reduces the amount of boilerplate code compared to additional conditionals such as if (this.formErrors.hasOwnProperty(field)).
Be careful with the answer, it might break your codes. Test after you "fix" it.
This doesn't actually remove the tslint error for me.
@HammerN'Songs check that you changed to for of instead of for in
same problem here. error is not removed after using this
Q
Qwertiy
for (const field in this.formErrors) {
  if (this.formErrors.hasOwnProperty(field)) {
for (const key in control.errors) {
  if (control.errors.hasOwnProperty(key)) {

P
Post Impatica

use Object.keys:

Object.keys(this.formErrors).map(key => {
  this.formErrors[key] = '';
  const control = form.get(key);

  if(control && control.dirty && !control.valid) {
    const messages = this.validationMessages[key];
    Object.keys(control.errors).map(key2 => {
      this.formErrors[key] += messages[key2] + ' ';
    });
  }
});

N
Nick

If the behavior of for(... in ...) is acceptable/necessary for your purposes, you can tell tslint to allow it.

in tslint.json, add this to the "rules" section.

"forin": false

Otherwise, @Maxxx has the right idea with

for (const field of Object.keys(this.formErrors)) {

Editing tslint.json....quick, easy and works great. Excellent answer!
l
lukas_o

I think this message is not about avoiding to use switch. Instead it wants you to check for hasOwnProperty. The background can be read here: https://stackoverflow.com/a/16735184/1374488