javascriptarrayspropertiesthisundefined

getting 'Cannot read property 'count' of undefined' in an if / else statement (Javascript)


i have an array appointment objects of which all each has this key: "RecurrenceRule". Either it is empty (null) or it has something of the following: "RecurrenceRule": "FREQ=DAILY;INTERVAL=1;COUNT=5;"

This is how one element looks like:

{ appointmentId: 001239,
    subject: "Something",
    Client: "Bob",
    StartTime: "2020-04-16T11:00:00.000Z",
    EndTime: "2020-04-16T11:30:00.000Z",
    km: 90,
    RecurrenceRule: null,
},

What I want to do is iterate through appointments by the .reduce() function and if the current element has "RecurrenceRule": "FREQ=DAILY;INTERVAL=1;COUNT=5;", I want to take the value after 'COUNT=' and assign it to count and if RecurrenceRule is null, I want to assign 1 to count, if that makes sense. Below is the method:

 export class AppointmentComponent implements OnInit {
appointments;


ngOnInit(){
this.getAppointments();
}


  getAppointments(){
this.appointmentService.getAppointments().subscribe((data : any) => {
  this.appointments= data.appointment;
  this.groupByClient();

});
 };

  groupByClient(){
  var result = [];

  this.appointments.reduce(function (res, value) {
    let diff = dayjs(value.EndTime).diff(dayjs(value.StartTime), "hour",true) % 60;
    if(res[value.RecurrenceRule] !== null) {
      let count =  parseInt(value.RecurrenceRule.split("COUNT=")[1])
    } else {
      let count =  1;
    }
    if (!res[value.Client]) {

      res[value.Client] = {
        km: value.km,
        Client: value.Client,
        count: this.count,
        difference: diff * this.count     
      };
      result.push(res[value.Client]);

    } else {
      res[value.Client].km += value.km;
      res[value.Client].difference += diff;
    }

    return res;
  }, {});
}
}

However, when I run this I get the error message: ERROR TypeError: Cannot read property 'count' of undefined, pointing to the this.count lines. What is going wrong here? Is it to do with the nested this. ?

If you need more info please let me know.


Solution

  • When you declare a variable with let, it is scoped to the block. In your case, count doesn't exist outside of if(…) {…} else {…}.

    You should write:

    let count;
    if(value.RecurrenceRule !== null) {
          count =  parseInt(value.RecurrenceRule.split("COUNT=")[1])
        } else {
          count =  1;
        }
    

    or:

    const count = value.RecurrenceRule
      ? parseInt(value.RecurrenceRule.split("COUNT=")[1])
      : 1;
    

    Later in your code, use count instead of this.count.