0

I'm trying to filter an array of objects. When i console.log the Array all the properties are filled with data but, when I use .filter it throws errors saying "Cannot read property 'id' of null.

Here is the code:

this.hubConnection.on('HorsesChanged', async (data: HorseModel[]) =>
  {
    if(await this.guard.checkPermission([PermissionType.SeeAllHorses]))
    {
      this.allHorses$.next(data)
    }
    else{
      console.log(data) //owner.id, jockey.id and trainer.id of all horses is filled
      this.allHorses$.next(data.filter(x=>x.owner.id==this.loggedInPersonId ||
      x.jockey.id==this.loggedInPersonId ||
      x.trainer.id==this.loggedInPersonId)) // throws error saying cannot read id of null 
    }
  }
);
  • You're running into [this feature of the console](https://stackoverflow.com/questions/38660832/console-log-of-element-children-shows-0-length-but-has-three-entries-when-expand). If you use an actual breakpoint on your `console.log` line and look at `data`, you'll see that `x.trainer` is undefined *at that time*. But later, when you expand the object in the console, it shows you what the object has *then, when you expanded it*. – T.J. Crowder Feb 06 '21 at 16:28
  • 1
    This is why rather than stumbling around in the dark with a `console.log` torch, you're better of *turning on the lights* with the debugger built into your browser and/or IDE. :-) Yes, sometimes `console.log` can be handy, but mostly the debugger gives you dramatically more information, and information that's accurate as of where you have the code paused. (If for some reason you can't use the debugger, you can do things like `console.log(JSON.stringify(data))` to capture what's in `data` at that moment in time. – T.J. Crowder Feb 06 '21 at 16:29

0 Answers0