Reputation: 1145
I'm getting a Javascript object in the following format
{
"Alerts": [{
"Name": "...",
"Type": "Warning",
"Message": "...",
"Time": "..."
},
{
"Name": "...",
"Type": "Critical",
"Message": "...",
"Time": "..."
},
{
"Name": "...",
"Type": "Info",
"Message": "...",
"Time": "..."
}]
}
How do I check if an alert of the type Critical exists anywhere in this array object I receive.
I am using angularjs.
Upvotes: 1
Views: 1112
Reputation: 21901
If you are searching angular kind of thing, Create a filter,
app.filter('checkCritical', function() {
return function(input) {
angular.forEach(input, function(obj) {
if((obj.Type).toLowerCase() == 'critical') {
return true;
}
});
return false;
};
})
use this filter inside the controller
in controller,
var exists = $filter("checkCritical").(Alerts);
dont forget to inject the $filter
in to the controller
Upvotes: 2
Reputation:
If you have jQuery on the page.
var exists = $.grep(alerts, function (e) { return e.Type == 'Critical'; }).length > 0;
Note: alerts
(as above) will be the array of alerts you have in your object there.
Reference:
http://api.jquery.com/jquery.grep/
Upvotes: 0
Reputation: 16837
You can do something like this
function find(arr, key, text){
for(var i = arr.length; i--;){
if(arr[i][key] === text) return i;
}
return -1;
}
Usage
var index = find(jsonObject.Alerts, "Type", "Critical")
Upvotes: 2
Reputation: 1700
You'll have to loop through each element of the array and check to see if any objects have 'Critical' as the Type property value.
Upvotes: -1