JS:筛选对象数组以进行部分匹配 [英] JS: Filter object array for partial matches
问题描述
是否可以过滤与搜索字符串匹配的那些对象?
Is it possible to filter for those objects, which matches for a search string?
const arr = [
{ title: 'Just an example' },
{ title: 'Another exam'},
{ title: 'Something different'}
]
我尝试过
arr.filter(x => { return x.title === searchStr });
但这将仅过滤完全匹配项,但是我需要找到所有部分匹配项. let searchStr = 'exam'
应该给我两个对象(第一个和第二个),let searchStr = 'examp'
应该给我一个对象.
But this will filter only exact matches, but I need to find all partial matches. let searchStr = 'exam'
should give me two objects (first and second), let searchStr = 'examp'
should give me only one object as the result.
推荐答案
根据您的问题,我假设您还希望同时匹配字符串的大写和小写版本,因此RegExps是正确的(但不是唯一的)选择
From your question I will assume you also want to match both uppercase and lowercase versions of your string, so here RegExps are the right (but not the only) choice.
首先,定义一个不区分大小写的 RegExp i
标志 a>,在循环之外(这避免了在每次迭代时重新创建新的RegExp实例):
First, define a case-insensitive RegExp with the i
flag, outside of the loop (this avoids re-creating a new RegExp instance on each iteration):
const regexp = new RegExp(searchStr, 'i');
然后,您可以使用 RegExp过滤列表#test ( String#match 也可以):
Then you can filter the list with RegExp#test (String#match would work too):
arr.filter(x => regexp.test(x.title))
String#includes解决方案:
您还可以使用 .includes
的String
方法,将两个字符串都转换为小写,然后再进行比较:
String#includes solution:
You could also use the .includes
method of String
, converting both strings to lowercase before comparing them:
arr.filter(x => x.title.toLowerCase().includes(searchStr.toLowerCase()))
这篇关于JS:筛选对象数组以进行部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!