正则表达式在JS过滤期间多次匹配同一对象

问题描述

我有一个对象people的列表,我想根据regex对其进行过滤。

{ name: 'Alice',city: 'London',country: 'UK',pet: 'dog',id: '12345' }

在获得fetched的{​​{1}}列表之后,我试图根据用户选择的过滤器对它们进行过滤。

people

因此,基本上,如果用户选择过滤器const nameString = request.body.name || null; const cityNameString = req.body.city || null; const countryNameString = req.body.country || null; const petNameString = req.body.pet || null; const idNameString = req.body.id || null; const peopleFiltered = people.filter(person => { if(nameString != null){ person = person.name.match(new RegExp('^' + nameString,'i')); } if(cityNameString != null){ person = person.city.match(new RegExp('^' + cityNameString,'i')); } if(countryNameString != null){ person = person.country.match(new RegExp('^' + countryNameString,'i')); } if(petNameString != null){ person = person.pet.match(new RegExp('^' + petNameString,'i')); } if(idNameString != null){ person = person.id.match(new RegExp('^' + idNameString,'i')); } return person; }) res.status(200).json(peopleFiltered); 并输入name,那么它将带出所有以aa开头的人。而且按预期工作,现在问题出在用户为同一查询选择多个过滤器时。

例如,如果用户选择过滤器A并输入一个值,然后选择第二个过滤器(例如name并为此输入一个值),则没有响应,因为它正在尝试匹配已经工作过的人。

首先,我该如何解决我的问题,其次,从结构上看,有没有更好的解决方案,因为这看起来不太好。

编辑 怎么了如果用户选择了2个过滤器,例如说petname,它将首先在第一个pet周期中进行match,然后将尝试再次进行匹配具有相同的if,但person的结果是match或用户输入的第一个["K"]

因此,它然后尝试再次使用NameString来执行match,但是由于它不再存在,因此会引发错误。

解决方法

这里的问题是,您在每次比赛后都要重新分配person,这使得事后检查无效

(非常)冗长的解决方案就是这样

const peopleFiltered = people.filter(person => {
  if(nameString) {
    const match = person.name.match(new RegExp('^' + nameString,'i'))
    if (match) {
      return true
    }
  }
  if(cityNameString) {
    const match = person.city.match(new RegExp('^' + cityNameString,'i'));
    if (match) {
      return true
    }
  }
  if(countryNameString) {
    const match = person.country.match(new RegExp('^' + countryNameString,'i'));
    if (match) {
      return true
    }
  }
  if(petNameString) {
    const match = person.pet.match(new RegExp('^' + petNameString,'i'));
    if (match) {
      return true
    }
  }
  if(idNameString) {
    const match = person.id.match(new RegExp('^' + idNameString,'i'));
    if (match) {
      return true
    }
  }
})

然后,当您了解发生了什么情况时,可以实现更优雅的解决方案,例如使用验证器函数和Array.some()

作为旁注,我建议您在使用时使用RegExp.test()而不是String.match(),这主要是因为您实际上并不需要匹配结果,而只需布尔值即可查看它是否签出是否

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...