Dhanushka Dolapihilla
Dhanushka Dolapihilla

Reputation: 1145

Check existence of an element in a nested javascript object array

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

Answers (4)

Kalhan.Toress
Kalhan.Toress

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

user1017882
user1017882

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

A1rPun
A1rPun

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

Ben Heymink
Ben Heymink

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

Related Questions