1

I have initializated array in Angular JS:

$scope.formData.universitySelected = [];

I try to fill array in loop:

 angular.forEach($scope.formData.university, function (value, key) {
    if (typeof value === 'object') {
         $scope.formData.universitySelected[key].id = value.IdEducation;
    } else {
        $scope.formData.universitySelected[key].selected = value;
    }
});

But I get error:

Cannot set property 'id' of undefined

2 Answers 2

2

You should create an object before using it.

angular.forEach($scope.formData.university, function (value, key) {
   $scope.formData.universitySelected[key] = $scope.formData.universitySelected[key] || {};
   if (typeof value === 'object') {
      $scope.formData.universitySelected[key].id = value.IdEducation;
   } else {
      $scope.formData.universitySelected[key].selected = value;
   }
});
Sign up to request clarification or add additional context in comments.

Comments

1

I think you need to define that object first then add value to in it.

Code

angular.forEach($scope.formData.university, function (value, key) {
    if (typeof value === 'object') {
         $scope.formData.universitySelected[key] = {id : value.IdEducation};
    } else {
        $scope.formData.universitySelected[key] = {selected : value.IdEducation};
    }
});

2 Comments

If $scope.formData.universitySelected[key] already exists, your code will remove any other properties.
@RobinJamesKerrison yes I know..before editing my answer..@hansmaad already added his answer..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.