现在有个需求,数据在前端做搜索 。
如:var data = [ {name:'',age:'',another:''},{name:'',age:'',another:''}];
关键字 var keywords = { name:'',age:'',another:''};
在data中查出符合keywords中的数据,可以只输入name查询其它不填,也可以输入name,age同时查询等。
这样的需求 ,怎么写?
现在有个需求,数据在前端做搜索 。
如:var data = [ {name:'',age:'',another:''},{name:'',age:'',another:''}];
关键字 var keywords = { name:'',age:'',another:''};
在data中查出符合keywords中的数据,可以只输入name查询其它不填,也可以输入name,age同时查询等。
这样的需求 ,怎么写?
输入name,但age不填的时候,可以设置此时的ageCondition=""。
搜索的时候,每个字段一个过滤器,链式组合。
然后调整搜索的匹配规则,(一般默认就是)使得搜索条件为空的时候显示全部。
这样 数据经过了 nameFilter 之后,就经过了name的筛选,再进入ageFilter,由于ageCondition="",直接相当于不过滤,这样最后得出的就是你要的结果。
var data = [{ name: '', age: '14', another: '' },
{ name: '222', age: '', another: '' }];
var keywords = { name: '222', age: '14', another: '' };
const deal = (arr, keywords) => {
return arr.filter(v => (keywords.name && v.name == keywords.name) || (keywords.another && v.another == keywords.another) || (keywords.age && v.age == keywords.age))
}
console.log(deal(data,keywords))
关键词不定的话
const deal =(arr,keywords)=>{
const arr2 = []
arr.forEach(v=>{
for(const key in keywords){
if(keywords[key]&&keywords[key]==v[key]){
arr2.push(v)
}
}
})
return arr2
}
data.filter(item => {
return (keywords.name == "" && keywords.name == item.name) || (keywords.age == "" && keywords.age == item.age) || (keywords.another == "" && keywords.another == item.another)
})
filterData(condition,data){
//condition 传入的是查询条件,是一个对象
//data 是本次需要筛选的数据源。
let filter = (condition, data) => {
return data.filter( item => {
return Object.keys( condition ).every( key => {
if(condition[ key ] == '') return true
//这里是为了进行某个条件的模糊查询做出的业务判断。key是对应的值。
let diff = key == 'gdsNm'
? String( item[ key ] ).toLowerCase().indexOf( String( condition[ key ] ).trim().toLowerCase() ) !== -1
: String( item[ key ] ).toLowerCase() == String( condition[ key ] ).trim().toLowerCase()
return diff
})
})
}
return filter(condition,data)
}
13 回答12.9k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
6 回答1.1k 阅读
3 回答1.3k 阅读✓ 已解决
每次搜索都是将name和age发送至后台,单个查询的时候只需要把另一个设置为空即可。