多筛选条件过滤数据.js 2.2 KB
Newer Older
Q
qq_42700109 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
// 对象数组筛选condition={dataKey:筛选条件。。。},data=需要筛选的数据
let data = [ {
        name: '国-红楼梦',
        price: 123,
        stock: 108
    }, {
        name: '国-西游记',
        price: 99,
        stock: 151
    }, {
        name: '国-水浒传',
        price: 708,
        stock: 72
    }, {
        name: '国-三国演义',
        price: 58,
        stock: 72
    }, {
        name: '外-荆棘鸟',
        price: 45,
        stock: 65
    }, {
        name: '外-格列佛游记',
        price: 69,
        stock: 151
    }, {
        name: '外-荷马史诗',
        price: 48,
        stock: 123
    } ]

function filter(condition, data){
    return data.filter( item => {
        return Object.keys( condition ).every( key => {
            return String( item[ key ] ).toLowerCase().includes(
                String( condition[ key ] ).trim().toLowerCase() )
        } )
    } )
}

//无条件
var condition={name: '',price: ''};
var aa = filter(condition,data);
console.log("=== 无条件 ===");
console.log(aa);

//单条件
var condition={name: ''};
var bb = filter(condition,data);
console.log("=== 单条件 ===");
console.log(bb);
//多条件
var condition={name: '',stock: 72};
var cc = filter(condition,data);
console.log("=== 多条件 ===");
console.log(cc);



let array = [ 
    { 
      date: '2022-05-02', 
      name: 'cuclife', 
      status: 'success', 
      tag: '70', 
     band:['R','B'] 
    }, 
     
    { 
      date: '2022-05-04', 
      name: 'Lily', 
      status: 'fail', 
      tag: '50', 
      band:['R','G'] 
    }, 
     
    { 
      date: '2022-05-01', 
      name: 'Kevin', 
      status: 'success', 
      tag: '20', 
      band:['R','G','B'] 
    }, 
    { 
      date: '2022-05-02', 
      name: 'Kevin', 
      status: 'success', 
      tag: '70', 
      band:['R','G','B','RE'] 
    }
]; 
 
let filterNames = ['Lily'];
let filterBand = ['R','G'];
let filterTag = ['50','70']; 
let result = array.filter((a,i)=>{ 
    return (filterNames.some(f => (f === a.name)) && filterTag.some(f => (f === a.tag)) || filterBand.some(f => (a.band.includes(f))) ) 
});

console.log(result);