Reputation: 1363
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
Upvotes: 0
Views: 128
Reputation: 1701
filter will create a new array every time, try this if all you need is to know if the object exists:
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"}
];
const includes = -1 !== obj1.findIndex(item => item.Type === "Faculty" || item.Type === "Staff" );
// in case your browser doesnt support arrow functions:
const includes2 =
-1 !== obj1.findIndex(
function (item) {
return item.Type === "Faculty" || item.Type === "Staff";
}
);
Upvotes: 3
Reputation: 2265
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');
Upvotes: 5
Reputation: 942
obj1.forEach(function(val,index){
if(val.type=='Faculty)
{
//your code
}
else if(val.type == 'Staff')
{
//your code
})
Upvotes: 0