在switch语句中对数组进行过滤的正确方法是什么
let filteredMachines = (filterTerm,filterField) => {
switch (filterField) {
case 'NomAppareil':this.props.machines.filter(machine => {
return machine.nomAppareil === filterTerm;
});
break;
case 'CodeAppareil':this.props.machines.filter(machine => {
return machine.codeAppareil === filterTerm;
});
break;
case 'NomClient':this.props.machines.filter(machine => {
return machine.nomClient === filterTerm;
});
break;
case 'CodeClient':this.props.machines.filter(machine => {
console.log('inside CodeClient ='+JSON.stringify(machine));
return (machine.codeClient == filterTerm);
});
break;
case 'NoSerie':this.props.machines.filter(machine => {
return machine.noSerie === filterTerm;
});
break;
default: return this.props.machines;
}
};
编辑:我找到了下面给出的工作解决方案
let filteredMachines = machines.filter((machine) =>{
switch (filterField) {
case 'NomAppareil': return machine.nomAppareil === filterTerm;
case 'CodeAppareil': return machine.codeAppareil === filterTerm;
case 'NomClient': return machine.nomClient === filterTerm;
case 'CodeClient': return machine.codeClient === filterTerm;
case 'NoSerie': return machine.noSerie === filterTerm;
default: return true;
}
});
答案 0 :(得分:2)
基本上你需要返回已过滤的数组(因此undefined
结果),然后你可以省略break语句。
case 'NomAppareil':
return this.props.machines.filter(machine => {
// ^^^^^^
return machine.nomAppareil === filterTerm;
});
// break;
或使用Set
代替switch
声明。
let filteredMachines = (filterTerm, filterField) => {
var set = new Set(['NomAppareil', 'CodeAppareil', 'NomClient', 'CodeClient', 'NoSerie']);
return set.has(filterField) ?
this.props.machines.filter(machine => machine[filterField] === filterTerm) :
this.props.machines;
};
答案 1 :(得分:0)
您可以执行以下操作;
var filters = ["NomAppareil","CodeAppareil","NomClient","CodeClient","NoSerie"],
result = filters.indexOf(filterField) !== -1 ? this.props.machines.filter(machine => machine[filterField] === filterTerm)
: this.props.machines;