简体   繁体   English

如何筛选具有多个条件的数据

[英]How to filter data with more than one condition

I have some alarm data in my list and i want to filter them based on some condition like if there are more than one alarm of type pull_Alarm and emergency_alarm in same location then give priority to emergency alarm. 我的列表中有一些警报数据,我想根据某种条件过滤它们,例如在同一位置是否有多个类型为pull_Alarm和Emergency_alarm的警报,然后将紧急警报优先。

Here is my list:
[
    {
        alarmType:"Normal_ALARM"
        location:"Ward5"
        severity:"URGENT"
    },
    {
        alarmType:"Emergency_Alarm
        location:"Ward1"
        severity:"URGENT"
    },
    {
        alarmType:"PULL_Alarm"
        location:"Ward1"
        severity:"NORMAL"
    }
]

What i want a list after filter should be only 我想要过滤器后的列表应该只是

[
  {
    alarmType:"Normal_ALARM"
    location:"Ward5"
    severity:"URGENT"
  },
  {
    alarmType:"Emergency_Alarm
    location:"Ward1"
    severity:"URGENT"
  }
]

Can someone suggest me how i can apply filter on these condition. 有人可以建议我如何在这些情况下应用过滤器。

Create one filter with switch cases or add if else conditions. 创建一个带有开关盒的过滤器,或者添加其他条件。

.filter("alarmFilter", function () {
    // write condition what ever you want to add
});

And apply this filter to your expression where you want to apply condition. 并将此过滤器应用于要应用条件的表达式。

Write filter 写过滤器

$scope.filter1 = function(item)
    {
        return (item.severity == 'URGENT');
    };

and then use it 然后用它

<div ng-repeat="item in object| filter:filter1">{{item.alarmType}}</div>

JSFIDDLE http://jsfiddle.net/Lvc0u55v/8866/ JSFIDDLE http://jsfiddle.net/Lvc0u55v/8866/

You can create a custom filter, as below. 您可以创建一个自定义过滤器,如下所示。

angular.module('myFilters', []).
filter('byAlarmCount', function() {
  return function(alarms, severity) {
    var items = {
      severity: severity,
      out = []
    };
    angular.forEach(alarms, function(v, k)) {
        if (this.severity[v.severity] === true) {
          this.out.push(v);
        }
      }
    return items.out;
  }
});

DOM as below DOM如下

<ul>
    <li ng-repeat="alarm in list | byAlarmCount:severityFilter">{{alarm.location}: {{alarm.alarmType}}</li>
</ul>

If you are looking to do some complex filtering then its better to look at some third party JS libraries like lodash ( https://lodash.com/ ) or Underscore ( http://underscorejs.org/ ). 如果您要进行一些复杂的过滤,则最好查看一些第三方JS库,例如lodash( https://lodash.com/ )或Underscore( http://underscorejs.org/ )。

These provide a wide range of utilities that can be used for filtering, mapping and other common utility functions. 这些提供了广泛的实用程序,可用于过滤,映射和其他常用实用程序功能。

For example for this current scenario you can use _.where / _.filter from underscorejs. 例如,对于当前情况,您可以使用underscorejs中的_.where / _.filter。

var filteredAlarms = _.where(<YOUR LIST>, { severity: NORMAL, alarmType: ...});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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