bort bort - 1 year ago 72
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 $ 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;
$ = data.category[0].info;
else if(val === 'cat2'){
$scope.catName = data.category[1].name;
$ = data.category[1].info;

Answer Source

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;
          $ = data.category[i].info;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download