【问题标题】:What is the best way to perform a RegEx test over multiple model fields?在多个模型字段上执行 RegEx 测试的最佳方法是什么?
【发布时间】:2018-11-24 12:51:12
【问题描述】:

如果我有以下型号:

data = [
  {comment: 'Blue eyes', label: 'Red', User: 'John Doe', total: 345},
  {comment: 'Bye', label: 'Blue', User: 'Jane Doe', total: 497},
  {comment: 'Whatever', label: 'Green', User: 'Blues Saraceno', total: 987}
]

我需要从现有的 filterString 中过滤结果。例如“蓝色” 什么是最好的申请方式:

const filterRegex = new RegExp(filterString, 'i')

到所有模型字段?刺痛是否在评论、用户、标签或总数中?

我非常感谢任何帮助。 谢谢

【问题讨论】:

  • 你想要什么结果?
  • 不要忘记正则表达式有它自己的特殊控制序列。所以你将无法搜索“(45)”而不像“\(45\)”一样转义它
  • 在这个特定的例子中,我希望有 3 条记录,因为它们的字段值中都有 blue
  • 如果过滤器只是一个单词而不是正则表达式,我会使用“includes(filterWord)”而不是正则表达式。

标签: javascript arrays regex functional-programming


【解决方案1】:

此算法将过滤数组和数组内的对象。将在对象中的所有值中查找 REGEXP 匹配项,并将返回至少具有匹配值的对象数组

希望这会有所帮助:)

var data = [
  {comment: 'Blue eyes', label: 'Red', User: 'John Doe', total: 345},
  {comment: 'Bye', label: 'Red', User: 'Jane Doe', total: 497},
  {comment: 'Whatever', label: 'Green', User: 'Blues Saraceno', total: 987}
]


const filterRegex = new RegExp('blue', 'i')

var newA = data.filter(el=>{
  let filterd = Object.values(el).filter(el=> el.toString().match(filterRegex) != null)
  if(filterd.length != 0)
  return el
})

console.log(newA)

【讨论】:

  • @LeonardoUribe 我的回答有帮助吗?如果您需要不同的东西,我很乐意编辑
【解决方案2】:

逻辑需要检查每个对象,但由于只有一个值需要匹配过滤器字符串,因此它只需要匹配其中一个值(即,如果已经发生匹配,则无需检查每个值)。这可以通过使用 filter 的本机 Array 方法来删​​除不匹配的对象和使用 some 的本机 Array 方法来完成每组对象值仅匹配一次。

函数看起来像这样:

function filter(filterStr, data) {
  const filterRegex = new RegExp(filterStr, 'i');

  // Iterate over data array and only return matching objects
  return data.filter((o) =>
    // Only check values until one matches
    Object.values(o).some((v) =>
      filterRegex.test(v)
    )
  );
}

还有一个工作示例:

const data = [{
    comment: 'Blue eyes',
    label: 'Red',
    User: 'John Doe',
    total: 345
  },
  {
    comment: 'Bye',
    label: 'Blue',
    User: 'Jane Doe',
    total: 497
  },
  {
    comment: 'Whatever',
    label: 'Green',
    User: 'Blues Saraceno',
    total: 987
  }
];

function filter(filterStr, data) {
  const filterRegex = new RegExp(filterStr, 'i');

  // Iterate over data array and only return matching objects
  return data.filter((o) =>
    // Only check values until one matches
    Object.values(o).some((v) =>
      filterRegex.test(v)
    )
  );
}

console.log(filter('Blue', data));

【讨论】:

    猜你喜欢
    • 2012-04-20
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2023-03-15
    相关资源
    最近更新 更多