H5W3
当前位置:H5W3 > 其他技术问题 > 正文

【Web前端问题】js 根据多条件(逻辑与)筛选数组数据

      const products = [
             {name:"华为P10",brand:'华为',price:'3488',code:'002'},
             {name:"小米MIX2",brand:'小米',price:'3599',code:'003'},
             {name:"小米6",brand:'小米',price:'2499',code:'004'},
             {name:"小米Note3",brand:'小米',price:'2499',code:'005'},
             {name:"iPhone7 32G",brand:'苹果',price:'4588',code:'006'},
             {name:"iPhone7 Plus 128G",brand:'苹果',price:'6388',code:'007'},
             {name:"iPhone8",brand:'苹果',price:'5888',code:'008'},
             {name:"三星Galaxy S8",brand:'三星',price:'5688',code:'009'},
             {name:"三星Galaxy S7 edge",brand:'三星',price:'3399',code:'001'}
          ];
          var chooses = [
               {
               type: 'brand',
               value: '华为'
              },
              {
               type: 'code',
               value: '001'
              }
          ]
          function choosesFilter(products,chooses){
              let tmpProducts = [];
           for (let choice of chooses) {
               console.log(choice)
            tmpProducts = tmpProducts.concat(products.filter(function (item) {
             return item[choice.type].indexOf(choice.value) !== -1;
            }));
           }
            console.log(tmpProducts);
          }
          choosesFilter(products,chooses);

我的初衷是获取brand为华为而且code为001的 数组数据,但是上述代码返回的是brand为华为或者code为001的 数组数据,怎么把上述的逻辑或筛选修改为逻辑与呢?

回答:

function choosesFilter(products,chooses){
    let tmpProducts = [];
    
    products.map((item)=>{
        //chooses.every((m)=>item[m.type] === m.value) && tmpProducts.push(item)
        //修改
        //if(chooses.every(function(m){return item[m.type] === m.value})){
        //修改
        if(chooses.every(function(m){
            return m.value?item[m.type] === m.value:true
           })){
            tmpProducts.push(item)
        }
    })
   
    console.log(tmpProducts);
}
choosesFilter(products,chooses);

本文地址:H5W3 » 【Web前端问题】js 根据多条件(逻辑与)筛选数组数据

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址