Ionic 3 & Firebase: pushing data to array of objects

I am trying to push an array of object from firebase and store it to my array attendance. But my code doesn’t work. Any idea how to do this?

Inside the for loop I tried to check if I am getting the data and it does iterate the name of the students. But it looks like the loop stops when it hits the code where I am pushing the data into the local array (attendance[])

export class CheckAttendancePage {

  public attendance: any[]
  public student: any[]

  constructor( private attendanceList: AttendanceListService, 
   public navCtrl: NavController, public navParams: NavParams) {

    attendanceList.getStudentsList().valueChanges().subscribe(students => {
      this.student = students;

      for (let index = 0; index < this.student.length; index++) {
        console.log(index)
        console.log(this.student[index].name)
        
        // problem here
        this.attendance.push({
        'studentName': this.student[index].name,
        'status': ''
        })
     }
     console.log("attendance", this.attendance)

  })
}

You should get an undefined function error for push, because you did not initialize the array for attendance. I your case attendance should be undefined when you try to call that push method.
You can fix that with:

public attendance: any[] = [];

Now it should work but if the studentslist changes a second time, you get the new list in your subscribe method and add it to the existing list of students. That way you will get duplicates inside the array. If you want to avoid that you could use the following:

export class CheckAttendancePage {

  public attendance: any[]
  public student: any[]

  constructor(private attendanceList: AttendanceListService,
    public navCtrl: NavController, public navParams: NavParams) {

    attendanceList.getStudentsList().valueChanges().subscribe(students => {
      this.student = students;
      this.attendance = students
        .map(student => ({
          studentName: student.name,
          status: ''
        }));
      console.log('attendance', this.attendance);
    });
  }
}
1 Like