snowflakes74
snowflakes74

Reputation: 1307

Loop and compare values in an array in Angular

I am trying to pre select checkboxes in angular 1.4 by comparing values in two arrays but for some reason my logic keeps omitting the first item in the array. My model that binds to checkboxlist is like below:

 $scope.weekDays = [{
    name: "Monday",
    value: false,
}, {
    name: "Tuesday",
    value: false,
}, {
    name: "Wednesday",
    value: false,
}, {
    name: "Thursday",
    value: false,
}, {
    name: "Friday",
    value: false,
}, ];

The value I receive from my db is

'Monday,Tuesday,Thurdsay'

I then split the value that I receive from my db into array and if the days name match in both the arrays I set the value as true which checks the checkbox.

 var PrefDays = 'Monday,Tuesday,Thursday';
 var selected_pref_days = new Array();

 selected_pref_days = PrefDays.split(',');

 for(var i = 0; i < selected_pref_days.length; i++) {
    console.log(selected_pref_days[i]);
     angular.forEach($scope.weekDays, function (day) {
       if (selected_pref_days[i] == day.name) {
           day.value = true;
        }
      })
  }

I expect to get $scope.weekDays to be like below:

$scope.weekDays = [{
name: "Monday",
value: true,
}, {
name: "Tuesday",
value: true,
}, {
name: "Wednesday",
value: false,
}, {
name: "Thursday",
value: true,
}, {
name: "Friday",
value: false,
}, ];

Instead I always get the first value as "false". Could someone please assist me ? Thank you

Upvotes: 0

Views: 1827

Answers (1)

DobleL
DobleL

Reputation: 3928

I can't find the issue but here is a simplest solution (and also easy to test and debug) that works for me. Sorry that I can not clarify your situation but at least you can keep coding on your final logic

$scope.weekDays = $scope.weekDays.map(d => {
    d.value = selected_pref_days.indexOf(d.name) != -1; 
    return d;
})

Upvotes: 1

Related Questions