Peter Boomsma
Peter Boomsma

Reputation: 9808

Check if a value is present in scope

I have a scope called $scope.activities. Inside that scope are multiple objects. Each object has a string called viewed with the value of check or uncheck. I would like to check if the value uncheck is present in the scope.

I've created this, but it doesn't seem to work.

if (activities.indexOf("uncheck") == -1) {
  console.log ('uncheck found')
  $scope.newActivities = 'newActivities';
} else {
  console.log ('no uncheck found')
}

Because in activities I have two objects, one with the uncheck value, and a object without it.

[{"id":2,", "viewed":"check"}, {"id":3,", "viewed":"uncheck"}]

Upvotes: 1

Views: 306

Answers (2)

AlainIb
AlainIb

Reputation: 4728

You have to loop over each object in the array and test if the property "viewed" equal to "unchek"

var activities  = [{"id":2, "viewed":"check"}, {"id":3, "viewed":"uncheck"}];
var activities2  = [{"id":2, "viewed":"check"}, {"id":3, "viewed":"check"}];
var check = function(data){
    var checked = false;
    for(var i in data){
        if(data[i].hasOwnProperty("viewed") && (data[i]["viewed"]=="uncheck") ){
            checked = true ;
        }
    }
    return checked;
} ;

console.log(check(activities));
console.log(check(activities2));

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

You've got to loop each object and check the property - you can use Array.some

var hasValue = activities.some(function(obj) { return obj.viewed == "unchecked" });

Upvotes: 2

Related Questions