在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ js 根據(jù)多條件(邏輯與)篩選數(shù)組數(shù)據(jù)

js 根據(jù)多條件(邏輯與)篩選數(shù)組數(shù)據(jù)

      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的 數(shù)組數(shù)據(jù),但是上述代碼返回的是brand為華為或者code為001的 數(shù)組數(shù)據(jù),怎么把上述的邏輯或篩選修改為邏輯與呢?

回答
編輯回答
遺莣
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);
2017年2月4日 20:56