过滤是否干燥?

时间:2018-12-24 02:57:10

标签: javascript

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原理?

2 个答案:

答案 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)))