bort bort - 3 months ago 5
Javascript Question

Compare function variable against array loop

I'm attempting to compare the value passed through the function (val) with items in an array (data.category) in order to replace my hard-coded 'cat1' and 'cat2' in the if/else statement. What I ultimately want to do is assign the appropriate $scope.catName and $scope.info for the appropriate value associated in the array.

How do I modify my code to iterate and compare?

$scope.changeRankingView = function(val){
var categoriesArray = data.category;
var categoriesArrayLength = categoriesArray.length;
for (var i = 0; i < categoriesArrayLength; i++) {
if(val === 'cat1'){
$scope.catName = data.category[0].name;
$scope.info = data.category[0].info;
}
else if(val === 'cat2'){
$scope.catName = data.category[1].name;
$scope.info = data.category[1].info;
}
}
};

Answer

I'm not completely sure I followed, but I think this would do what you are asking:

$scope.changeRankingView = function(val) {
    for (var i = 0; i < data.category.length; i++) {
        if(val === data.category[i]){
          $scope.catName = data.category[i].name;
          $scope.info = data.category[i].info;
        }
    }
 };

I used data.category directly, because it didn't seem like categoriesArray was adding anything useful.

Comments