Pravin Pravin - 1 year ago 142
AngularJS Question

compare with angular object

Following my angular object

$scope.obj1= [

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') {

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

if ( myobj[i].Type == 'Staff') {

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

Answer Source
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.

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download