Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
use underscore.js. you can use find method. –  entre Oct 20 '14 at 9:57
    
Or lodash stackoverflow.com/questions/13789618/… –  Ben Heymink Oct 20 '14 at 9:59
    
if(data.Alerts.filter(function pluck(a){return a[this]}, "Message").indexOf("Critical")!==-1){ alert("oh noes!");} –  dandavis Oct 20 '14 at 10:00

4 Answers 4

up vote 2 down vote accepted

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

share|improve this answer

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")
share|improve this answer

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/

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.