如何根据多个字段匹配出当前对象
需求是一个搜索匹配功能,输入searchVal根据name path,查出符合的对象,用户可能根据 name中文搜索也可能根据path搜索,所以得匹配两个字段,
比如输入一个i应该筛选出所有,因为 详情页得path字段里也带有i
输入s的话,应该匹配出 2和3,输入中文也是同理,
[ {
name:'首页',
path:'/index'
},
{
name:'列表页',
path:'/list'
},
{
name:'详情页',
path:'/details'
}
]
回答:
const onSearch = (list = [], keyList = [], value) => { let newList = list;
if (value) {
newList = newList.filter((e) => {
for (let i = 0; i < keyList.length; i++) {
const key = keyList[i];
if(e[key] && e[key].includes(value)){
return true;
}
}
return false;
});
}
return newList;
};
回答:
[ {
name:'首页',
path:'/index'
},
{
name:'列表页',
path:'/list'
},
{
name:'详情页',
path:'/details'
}
].filter(item => item.name.includes('i') || item.path.includes('i'))
模糊查询
回答:
function match<T extends Record<string, string>>( list: T[],
fields: (keyof T)[],
key: string
) {
return list.filter((x) => {
return fields.some((field) => x[field].includes(key));
});
}
function match(list, fields, key) { return list.filter((x) => fields.some((field) => x[field].includes(key)));
}
以上是 如何根据多个字段匹配出当前对象 的全部内容, 来源链接: utcz.com/p/937215.html