1

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.

Dhanushka Dolapihilla
  • 1,115
  • 3
  • 17
  • 34

4 Answers4

2

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")
A1rPun
  • 16,287
  • 7
  • 57
  • 90
2

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

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
0

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/

-1

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.

Ben Heymink
  • 1,700
  • 12
  • 26