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

Javascript 在JS中过滤期间多次匹配同一对象的正则表达式,javascript,regex,filter,match,Javascript,Regex,Filter,Match,我有一个对象列表人,我想根据regex对它们进行过滤 { name: 'Alice', city: 'London', country: 'UK', pet: 'dog', id: '12345' } 在获取了人员列表后,我将尝试根据用户选择的过滤器对其进行过滤 const nameString = request.body.name || null; const cityNameString = req.body.city || null; const countryName

我有一个对象列表
,我想根据
regex
对它们进行过滤

{ name: 'Alice',
  city: 'London',
  country: 'UK',
  pet: 'dog',
  id: '12345' }
获取了
人员列表后,我将尝试根据用户选择的过滤器对其进行过滤

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);
因此,基本上,如果用户选择过滤器
名称
并输入
a
,则会显示所有以
a
a
开头的人。正如预期的那样,现在当用户为同一个查询选择多个过滤器时,问题就出现了

因此,例如,如果用户选择过滤器
name
并输入一个值,然后选择第二个过滤器,例如
pet
,并为此输入一个值,则不会有响应,因为它正试图匹配一个已经工作过的人

首先,我如何解决我的问题,其次,是否有一个更好的解决方案结构,因为这看起来不太好

编辑 出了什么问题。如果用户选择了2个过滤器,比如说
name
pet
,它将首先在第一个
If
循环中进行
匹配
,然后它将尝试再次与相同的
人进行匹配,但是
匹配的结果是
[“K”]
或任何用户输入的第一个
名称字符串


因此,它尝试再次与
person.pet进行
匹配
,但由于它不再存在,因此会引发错误。

这里的问题是,您在每次匹配后重新分配
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
    }
  }
})
然后,当您了解发生了什么时,就可以实现一个更优雅的解决方案,比如使用验证器函数和


作为补充说明,我建议使用,而不是像您使用的那样,主要是因为您并不真正需要匹配结果,而只需要布尔结果来查看它是否签出

当前的输出是什么?出了什么问题?编辑了这个问题。这里“返回true”的目的是什么?@kataroty需要一个返回truthy/falsy的函数来进行过滤,在我们明确提到的示例中“如果这是一场比赛,那么保留它,如果不是,那么继续寻找其他比赛。这就是为什么我不建议直接返回比赛,因为你会被第一次检查(nameString)卡住