george
george

Reputation: 97

javascript/angularjs looping through an array show only one object

in angularjs modal i am trying to display all classes that have level 4 but i got only one. please how should i alter my could in order to get all the class

$scope.openClass = function (classes) {
    $log.info("classes",classes);
    var modalInstance = $modal.open({
        templateUrl: 'classes.html',
        controller: 'ModalClassInstanceCtrl',
        resolve: {
            info: function () {
                var info = {};
                for (var i=0;i<classes.length;i++){                     
                    if (classes[i].level==4){                           
                        info['name']= classes[i].name;
                        $log.info("classinfo",info);                            
                    }
                }                   
                $log.info(info);
                return info;
            }
    }
});

the $log in if condition show me the write classes they are two in my case but the $log after the for loop show me only one

Upvotes: 0

Views: 55

Answers (2)

developer033
developer033

Reputation: 24874

You could use the filter method, as the following:

var filteredArray = classes.filter(function(value) {
   return value.level == 4;
));

After it, if you want to pluck only the name of those items you can do the following:

var names = filteredArray.map(function(obj) {
  return obj.name;
}

If you are going to do this often, you could write a function that abstracts away the map, this way:

function pluck(array, key) {
  return array.map(function(item) {
    return item[key]; 
  }); 
}

Upvotes: 1

Andrew Medvedsky
Andrew Medvedsky

Reputation: 93

I think, you overwrite you param "name"

info['name']= classes[i].name;

If you want collection, you should

var info = [];
info.push(classes[i].name)

Upvotes: 0

Related Questions