TheUnreal
TheUnreal

Reputation: 24472

forEach() inside filter()

I have the following method:

getDeviceErrors(error) {
this.devices = this.data.segment.data.devices.filter((device) => {
          device[this.data.label].error.forEach((errorObj) => {
            if (errorObj.id === error.id) {
              console.log(true);
              return true;
            }
        });
      });
}

Although true is outputted to the console, this.devices is still empty.

Any idea why?

Upvotes: 1

Views: 2264

Answers (1)

str
str

Reputation: 44969

Your filter function does not actually return anything. To fix this, you could use Array.prototype.some as follows:

getDeviceErrors(error) {
    this.devices = this.data.segment.data.devices.filter((device) => {
        return device[this.data.label].error.some((errorObj) => {
            return errorObj.id === error.id;
        });
    });
}

And by the way: I would expect a function called getDeviceErrors to return something and not just change the state.

Upvotes: 7

Related Questions