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

最佳答案

使用属性数组,后跟.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))
);

10-06 15:04