1

I want to loop through the student list which I received from a REST service located on a server. this list contains objects for students enrolled in a section. Each object has firstName, lastName, student ID and many other attributes, specifically an attribute called isAbsent. Its a Boolean value where it has true if the student is absent and false if the student is present in not absent. I want to store the students IDs who are absent (have isAbsent=true) in another String Array.

I tried this :

{ 
    //this array will store the IDs of students who are absent.
    $scope.selection = [];
    //$scope.studentList is the list of students for CRN=X and Date=Y
    for (id in $scope.studentList) {
        if ($scope.studentList.isAbsent === true) {
            $scope.selection.push($scope.studentList.id);
            console.log($scope.selection);
        }
    }
}

This code doesn't execute. I have no clue why, I guess the problem in the loop structure. Any help?

0

2 Answers 2

3

Maybe this will help?

for (var i=0;i<$scope.studentList.length;i++)
{
    if ($scope.studentList[i].isAbsent === true) 
    {
        $scope.selection.push($scope.studentList[i].id);
        console.log($scope.selection);
    }
} 

p.s. don't use for..in with arrays. It will display an index instead of a value. It's not like C#.

Sign up to request clarification or add additional context in comments.

4 Comments

It worked fine, but I need some clarifications: When I type studentList then followed by dot, I did not get the associated method "length" for this List. Does that mean we modified the prototype of the list?
'm not sure i understand your question
I'm using Netbeans 8.0, I meant, that when I type studentList I expect to see dropdown suggestions list for the methods that are applied on this list, for example, studentList.getOwnPropertyNames() and studentList.defineProperty() which are suggestion by the IDE. However, the method studentList.length doesn't show up in this list of suggestions.
IMHO netbeans is for java . not javascript. also - becuase $scope is a complex object ( very complex) - it's hard for autocomplete to realize that studentList is array.
3

Depending on what browsers you need to support (e.g. IE >= 9), I'd suggest the newer foreach construct. I find it easier to use:

$scope.studentList.forEach(function(value, index, array) {
    if (value.isAbsent === true) 
    {
        $scope.selection.push(value.id);
        console.log($scope.selection);
    }
});

Comments

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.