Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property push of null

while pushing an element for the first time to a child array which is null,I'm getting this error "Cannot read property push of null" But the element gets pushed,and the second time I do everything goes fine.It gets added to the array

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

group contains the data and departmentList is the child array which is declared like this:

 $scope.parentDepartment = [
    {
        departmentsList: [{}]
    }
];
like image 382
forgottofly Avatar asked Oct 09 '14 07:10

forgottofly


1 Answers

Well don't push to nonexistent array maybe? You can explicitly check if it's not null and create one if needed:

this.group.departmentsList = this.group.departmentsList || [];
this.group.departmentsList.push({
    name: group.newCategoryName,
    sortOrder: group.departmentsList.length,
    type: "category"
});
like image 131
dfsq Avatar answered Sep 19 '22 15:09

dfsq