简体   繁体   中英

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.

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")

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

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/

您必须循环遍历数组的每个元素,并检查是否有任何对象具有“严重”作为Type属性值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM