Unable to read push null property

the first time an element is clicked on a child array that is null, I get this error Msgstr "Unable to read the push null property" But the element is pressed, and the second time I do everything well. It is added to the array.

this.group.departmentsList.push({
    name: group.newCategoryName,
    sortOrder: group.departmentsList.length,
    type: "category"
});
Group

contains data, and departmentList is a child array, which is declared as follows:

 $scope.parentDepartment = [
    {
        departmentsList: [{}]
    }
];
+4
source share
1 answer

Well, don't push into a nonexistent array? You can explicitly check if it is not null and create it if necessary:

this.group.departmentsList = this.group.departmentsList || [];
this.group.departmentsList.push({
    name: group.newCategoryName,
    sortOrder: group.departmentsList.length,
    type: "category"
});
+5
source

All Articles