1、 如果所有字段全部过滤
function multiQuery(arr, q) {
return arr.filter((v) => {
return Object.values(v).some((v) => new RegExp(q + '').test(v))
})
}
2、 如果指定部分字段进行过滤
function multiQuery(arr, q, attr) {
return arr.filter((v) => {
const filteredObject = Object.fromEntries(
Object.entries(v).filter(([key]) => attr.includes(key))
)
return Object.values(filteredObject).some((v) => new RegExp(q + '').test(v))
})
}
举例分析
const arr = [
{ title: 'title1', name: 'aaaa', description: 'AAAAAA' },
{ title: 'title2', name: 'bbbb', description: 'BBBBBBB' },
{ title: 'title3', name: 'ccccc', description: 'CCCCCC' }
]
const filteredAttr = { 'name' , 'description' }
const filteredObject = Object.fromEntries(
Object.entries(v).filter(([key]) => attr.includes(key))
)
// 打印结果就是 { name: 'aaaa', description: 'AAAAAA' }
// { name: 'bbbb', description: 'BBBBBBB' }
// { name: 'ccccc', description: 'CCCCCC' }
这个里 filteredObject打印出来 { name: 'aaaa', description: 'AAAAAA' }
过滤出来两个属性,然后再进行关键字过滤
multiQuery(arr, 'c', filteredAttr)
// 打印结果就是 [ { title: 'title3', name: 'ccccc', description: 'CCCCCC' } ]