简体   繁体   English

使用JavaScript过滤器功能时使用通配符

[英]Using wildcards while using JavaScript filter function

I have an array of objects in which I need to do wildcard filtering. 我有一个对象数组,需要在其中进行通配符过滤。 For example, my object might contain something like this: 例如,我的对象可能包含以下内容:

var a = [  
   {  
      "type":"metals",
      "SN":"SN0000000000"

   },
   {  
      "type":"wood",
      "SN":"SN0000000001"
   }
];

My filtering function for normal criteria would be something like: 我对正常条件的过滤功能如下所示:

  var filtered = a.filter(function(el) {
      //normal checkbox criteria filter for selectedtype
      if(!(self.serialno)){
        return el.type == self.selectedType
      }
      //wildcard text filtering from textfield
      else{
       return typeof el.SN == self.serialno;
      }
    });

And printing out of results would be something like: 打印出的结果将是这样的:

console.log(filtered);

For normal criteria filter ("type") in which i'm using checkbox criteria selection , I'm able to get my selected criteria type back(as an array of objects), but in the case of "SN" in which invokes text-based wildcard search , I'm unable to do so. 对于我正在使用复选框条件选择的普通条件过滤器(“类型”),我可以取回我选择的条件类型(作为对象数组),但是在“ SN”的情况下调用文本基于通配符的搜索,我无法执行此操作。

For example, If I were to key in "00" in my wildcard textfield, the function supposed to return an array of objects in which "SN/serialNo" contains "00" (in the example above, both objects in var a ). 例如,如果我在通配符文本字段中键入“ 00”,则该函数应该返回对象数组,其中“ SN / serialNo”包含“ 00”(在上面的示例中,两个对象都在var a中 )。

PS: PS:

self.serialno is a string that is retrieved from the textbox. self.serialno是从文本框中检索的字符串。

el.SN is the array of objects returned from the filter function. el.SN是从过滤器函数返回的对象的数组。

Update: 更新:

running this code: 运行此代码:

console.log(self.serialno.test(el.SN));

returns me : 返回我:

在此处输入图片说明

As far as I understand from your question you el.SN is a string representing a set of serial number conform to a regular expression. 据我从您的问题中了解到, el.SN是代表一组符合正则表达式的序列号的字符串。 If so you can use the test function which is aimed at testing the invoking string against a regular expression passed as parameter. 如果是这样,则可以使用test功能,该功能旨在针对作为参数传递的正则表达式测试调用字符串。

  var patt = new RegExp(self.serialno);
  if(patt.test(el.SN)){ return el; }

returns true if self.serialno match with the regular expression el.SN 如果self.serialno与正则表达式el.SN匹配,则返回true

You say el.SN is the result of the javascript filter function. 您说el.SN是javascript过滤器功能的结果。 I think however the filtered variable contains the result of that function. 我认为但是filtered变量包含该函数的结果。

el.SN is rather a property of a parameter ( el ) passed to the function used to filter the array a . el.SN是传递给用于过滤数组a的函数的参数( el )的属性。

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

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