躍然一笑
2019-03-13 17:14:32
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ù),怎么把上述的邏輯或篩選修改為邏輯與呢?
1 回答

幕布斯7119047
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
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);
添加回答
舉報(bào)
0/150
提交
取消