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 中链接动态标准?谢谢
使用 obj 而不是数组
const arr = [
{label : 'lbl1', text: 'txt1'},
{label : 'lbl2', text: 'txt2'},
{label : 'lbl3', text: 'txt3'},
{label : 'lbl4', text: 'txt4'},
];
const filterBy = {
criteria1:"lbl1",
criteria2:"txt1",
criteria3:"lbl4",
criteria4:"txt2",
}
const filtered = arr.filter(item => filterBy["criteria1"] === item.label ||filterBy["criteria2"] === item.text)||filterBy["criteria3"] === item.label || filterBy["criteria4"] === item.text);
其他“解决方案”必须进行两个或更多循环。而这个只需做一个。
而标准越多,看起来就越丑