0

I have an array that is always undefined inside a forEach, even when I initialize it before entering the forEach:

    this.deletedPersons =  new Array<PersonMasterBase>();

    selectedPersons.forEach(function (value) {
      let index = allPersons.findIndex(p => p.p_PersonID == value.p_PersonID);
      if (index < 0)
      {
        return false;
      }
      else
      {
        this.deletedPersons.push(allPersons[index]);
        allPersons.splice(index, 1);
      }

    });

Any references I find online deal with the array that is the subject of the forEach, rather than a 'third party' as in my case.

The error occurs on the line where I push to this.deletedPersons and its text is:

 'TypeError: Cannot read properties of undefined (reading 'deletedPersons')\n    
 at http://localhost:4200/main.js:8200:30\n    
 at Array.forEach (<anonymous>)\n    
 at http://localhost:4200/main.js:8191:33\n    
 at http://localhost:4200/vendor.js:35305:37\n    
 at OperatorSubscriber._next (http://localhost:4200/vendor.js:34722:21)\n    
 at OperatorSubscriber.next (http://localhost:4200/vendor.js:33551:18)\n    
 at OperatorSubscriber.onFinalize (http://localhost:4200/vendor.js:34141:36)\n    
 at OperatorSubscriber.unsubscribe (http://localhost:4200/vendor.js:34761:88)\n    
 at OperatorSubscriber._complete (http://localhost:4200/vendor.js:34751:26)\n    
 at OperatorSubscriber.complete (http://localhost:4200/vendor.js:33569:18)'
Ger
  • 169
  • 1
  • 11
  • 1
    The forEach callback calls an Array method on `allPersons` and `this.deletedPersons`. If either isn't an array, you'll get an error. Since we can rule out `this.deletedPersons`, it's probably `allPersons`. Is it supposed to be `this.allPersons` maybe? Also please always state the error you're getting and point out the line it references. –  Aug 27 '22 at 09:45
  • I'v e just added that detail now – Ger Aug 27 '22 at 10:03
  • 2
    @ChrisG Don’t rule out `this.deletedPersons`…! – deceze Aug 27 '22 at 10:05
  • 1
    @deceze True, I missed it's not an arrow function. –  Aug 27 '22 at 11:04

1 Answers1

2

The this in forEach function is referring to the current scope(forEach) and not the class itself, so this.deletedPersons inside forEach means your are trying to access the deletedPersons declared in forEach which is obviously not.
the solution to this is to whether to use arrow function as:

selectedPersons.forEach((value) => {
      let index = allPersons.findIndex(p => p.p_PersonID == value.p_PersonID);
      if (index < 0)
      {
        return false;
      }
      else
      {
        this.deletedPersons.push(allPersons[index]);
        allPersons.splice(index, 1);
      }

    });

Or assign the this.deletedPersons to any other variable like allPersons maybe deletedPersonsList