const arr = [ {label : 'lbl1', text: 'txt1'}, {label : 'lbl2', text: 'txt2'}, {label : 'lbl3', text: 'txt3'}, {label : 'lbl4', text: 'txt4'}, // 更多项目];const filterBy = ...
const arr = [
{label : 'lbl1', text: 'txt1'},
{label : 'lbl2', text: 'txt2'},
{label : 'lbl3', text: 'txt3'},
{label : 'lbl4', text: 'txt4'},
// much more items
];
const filterBy = [
{label: 'lbl1',text: 'txt1'},
{label : 'lbl4', text: 'txt4'}
//may have 0 or more items
];
我想 动态地 过滤 arr
来自 filterBy
. filterBy
UI 的内容...这里它只是表示用户可以传递的内容...
我会以静态的方式做:
arr.filter(x => (x.text == filterBy[0].text && x.label == filterBy[0].label) ||
. (x.text == filterBy[1].text && x.label == filterBy[1].label)
);
是否可以在 JS 中链接动态标准?谢谢
您可以使用reduce并在回调中使用filter来获取项目 arr
const arr = [{
label: 'lbl1',
text: 'txt1'
},
{
label: 'lbl2',
text: 'txt2'
},
{
label: 'lbl3',
text: 'txt3'
},
{
label: 'lbl4',
text: 'txt4'
},
//.... much more items
];
const filterBy = [{
label: 'lbl1',
text: 'txt1'
},
{
label: 'lbl4',
text: 'txt4'
}
];
const res = filterBy.reduce((acc, curr) => {
acc.push(...arr.filter(item => {
return item.label === curr.label && item.text === curr.text
}))
return acc;
}, []);
console.log(res)