Pravin Pravin - 2 months ago 9
AngularJS Question

compare with angular object

Following my angular object

$scope.obj1= [
{"NewID":38,"Type":"Faculty","Year":"2016","Status":"Active"},
{"NewID":39,"Type":"Staff","Year":"2016","Status":"Active"},
{"NewID":40,"Type":"Faculty","Year":"2016","Status":"Active"},
{"NewID":41,"Type":"Faculty","Year":"2016","Status":"Active"}
]


I want to check 'Type' contains any 'Staff' or 'Faculty' for that I use following code

var myobj=$scope.obj1;

var x=false; y=false;

for (var i = 0; i < myobj.length; i++) {
if ( myobj[i].Type == 'Faculty') {
x=true;
break;
}

}
for (var i = 0; i < myobj.length; i++) {

if ( myobj[i].Type == 'Staff') {
y=true;
break;
}
}


i used JavaScript for that i am looking for easy way in angular or JavaScript rather than using for loop

Answer
var filteredObjects = $scope.obj1.filter(function(obj){
   return obj.Type === 'Faculty' || obj.Type === 'Staff';
})

This will return you an array with the filtered objects (Type 'Faculty' and 'Staff'). You can check the length to see if there's any or do any other operations you need.

EDIT
Since you only want to check if it contains any 'Faculty' or 'Staff' you should use Array.prototype.some instead.

var exists = $scope.obj1.some(function (obj) { 
    return obj.Type === 'Faculty' || obj.Type === 'Staff';
}

For separate result you could just create the function

function checkExists (type) {
    return $scope.obj1.some(function (obj) { 
        return obj.Type === type;
    }
}
var facultyExist = checkExists('Faculty');
var staffExist = checkExists('Staff');
Comments