结合使用filter()和include()获得部分匹配 [英] Using filter() in combination with includes() to get partial matches
问题描述
我有一个数组,其中包含要搜索的对象.可搜索数组如下所示:
I have an array with objects I want to search through. The searchable array looks like this:
[
{ value: 0, label: 'john' },
{ value: 1, label: 'johnny' },
{ value: 2, label: 'peter' },
{ value: 3, label: 'peterson' }
]
我使用Lodash过滤器方法进行搜索:
I search through this using the Lodash filter method:
search = (text) => {
let results = _.filter(
this.props.options,
{ label: text }
);
}
这仅显示与搜索查询(text
参数)完全匹配的结果.我需要通过部分匹配来完成这项工作.因此,如果我插入j
或johnny
,它应该能够同时找到'John'和'Johnny'.
This only shows the result that exactly matches the search query (text
parameter). I need to make this work with partial matches. So if I insert j
or johnny
it should be able to find both 'John' and 'Johnny'.
我尝试过:
search = (text) => {
let results = _.filter(
this.props.options =>
this.props.options.includes({ label: text })
);
}
但是,没有运气.没有错误,没有结果.我该如何进行这项工作?
But, no luck. No error and no results. How can I make this work?
推荐答案
那不是您使用String.prototype.includes
的方式.您应该为其提供一个字符串,而不是一个对象.并且您应该提供一个包装对includes
:
That's not how you use String.prototype.includes
. You should provide a string to it not an object. And you should provide a function that wraps the call to includes
:
search = (text) => {
let results = _.filter(
this.props.options, // first parameter to _.filter is the array
option => option.label.includes(text) // the second parameter is a funtion that takes an option object and returns a boolean (wether the label of this option includes the text text or not)
);
}
这篇关于结合使用filter()和include()获得部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!