[英]Elegant way to do multiple parameter filter for client-side search
So, say I have an object that looks like the following:所以,假设我有一个如下所示的对象:
const DEVICES: { mac: string; name: string; ip: string; type: number }[] = [
{
mac: 'xx:xx:xx:xx:xx',
name: 'something',
ip: 'xx.xx.xx.xx.xx',
type: 0,
},
{
mac: 'xx:xx:xx:xx:yy',
name: 'something1',
ip: 'xx.xx.xx.xx.yy',
type: 1,
},
// and so on...
];
When I wanted to have multiple searchable parameters (name, mac, ip) - what's intuitive to me is to put some ||
当我想要多个可搜索参数(名称、mac、ip)时 - 对我来说直观的是放一些
||
(ORs) inside my filter function like: (OR)在我的过滤器功能中,例如:
DEVICES.filter((item) => {
return item.name.toLowerCase().indexOf(dataFromInputEvent.trim().toLowerCase()) >= 0
|| item.ip.toLowerCase().indexOf(dataFromInputEvent.trim().toLowerCase()) >= 0
|| item.mac.toLowerCase().indexOf(dataFromInputEvent.trim().toLowerCase()) >= 0;
})
.map(item, index) = {
return (
<SomeComponent
key={index}
type={item.type}
name={item.name}
mac={item.mac}
type={item.type}
/>
);
)}
as you can see, if the data gets more properties and if I were to add another parameter for search, I would just put another ||
如您所见,如果数据获得更多属性,并且如果我要添加另一个搜索参数,我会添加另一个
||
inside the filter function to return.在过滤器函数中返回。 Is there a more elegant way to to do multiple parameter search - ideally without repeating the same
toLowerCase()
and indexOf()
?有没有更优雅的方法来进行多参数搜索 - 理想情况下不重复相同的
toLowerCase()
和indexOf()
? or maybe not doing the ||
或者也许不做
||
thing altogether?一共事?
Create an array of the properties to filter (currently, ['name', 'ip', 'mac']
), then iterate over them and see if .some
of them, when accessed with bracket notation on item
, include the data:创建一个要过滤的属性数组(当前为
['name', 'ip', 'mac']
),然后遍历它们并查看.some
的一些在使用item
上的括号表示法访问时是否包含数据:
DEVICES.filter((item) => {
const input = dataFromInputEvent.trim().toLowerCase();
return ['name', 'ip', 'mac'].some(prop => item[prop].toLowerCase().includes(input));
})
.map( // ...
(note that you can make the code much less repetitive by storing the trimmed and lower-cased input in a variable first, and by using .includes
instead of indexOf
) (请注意,您可以通过首先将修剪后的小写输入存储在变量中,并使用
.includes
而不是indexOf
来减少代码的重复性)
You also probably meant to type DEVICES
as an array of objects, not a single object:您可能还打算将
DEVICES
键入为对象数组,而不是单个对象:
const DEVICES: Array<{ mac: string; name: string; ip: string; type: number }> = [
But Typescript can almost infer types without you having to explicitly note them, so但是 Typescript 几乎可以推断类型,而无需您明确指出它们,所以
const DEVICES = [
alone would probably be enough.单独可能就足够了。 (less code to write means less surface area for errors, and often also makes things more readable)
(编写更少的代码意味着更少的错误表面积,并且通常也使事情更具可读性)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.