list = list.filter(({ field1, field2, field3, field4, field5, field6, field7}) => {
let found = false;
if (field1.includes(this.state.filterString) ||
field2.includes(this.state.filterString) ||
field3.includes(this.state.filterString) ||
field4.includes(this.state.filterString) ||
field5.includes(this.state.filterString) ||
field6.includes(this.state.filterString) ||
field7.includes(this.state.filterString) ||
) {
found = true;
}
return found
});
上面的代码看起来很重复,我想知道是否有可能使其更简洁或不违反DRY原理?
答案 0 :(得分:4)
使用一组属性,然后进行.some
测试:
const itemProperties = ['field1', 'field2', 'field3', 'field4', 'field5', 'field6', 'field7'];
const { filterString } = this.state;
const filteredList = list.filter(
item => itemProperties.some(prop => item[prop].includes(filterString))
);
答案 1 :(得分:0)
如果您要处理要通过每个键检查过滤字符串的对象,也可以使用Object.values()
:
list.filter(item => Object.values(item).some(prop => prop.includes(filterString)))