angulartypescriptruntime-errorundefined

Angular - TypeError: Cannot read properties of undefined (reading 'forEach')


I am trying to read the roles array from this object and getting the error:

TypeError: Cannot read properties of undefined (reading 'forEach')

Code:

this.data.roles.forEach(role => {

  this.roleIds.push(role.id); // roleIds is another array of numbers I have defined.

})

data:

{
    "userID": "abcd",
    "firstName": "FNU",
    "allowedOffices": [
    "lastName": "LNU",
    "roles":[ 
        {
            "id":"ABC",
            "name": "Read"
        },
                {
            "id":"XYZ",
            "name": "Write"
        }
    ]
}


this.data.roles.forEach(role => {

  this.roleIds.push(role.id); // roleIds is another array of numbers I have defined.

})

Solution

  • From what I can tell from your code, it may have something to do with how you're defining the array within the Angular lifecycle.

    export class Component implements OnInit {
      data: any; //Or if you want to TYPE this for your JSON data
      roleIds: any = [];
    
      constructor() {
          this.data = // Your JSON DATA
      }
    
      ngOnInit() {
        this.data.roles.forEach(role => {
            this.roleIds.push(role.id);
         }
      }
    }
    

    Could also implement an interface if you're dealing with other issues from reading the JSON object if you'd like. Something akin to this would probably work for your purposes:

    interface UserData {
      userID: string;
      firstName: string;
      allowedOffices: any[];
      lastName: string;
      roles: {
        id: string;
        name: string;
      }[];
    }
    

    Please note that in your example, allowedOffices doesn't have a closing bracket and could mean that you don't have access to roles from where you're grabbing it currently (i.e., you'd need to grab this.data.allowedOffices.roles to get what you want).

    Hope it helps! ✨