参数用于过滤数组的属性

时间:2018-12-13 14:39:41

标签: javascript angular typescript

我有两个几乎相同的函数,除了它们比较数组内对象的不同属性。有没有一种方法可以将该属性作为参数,然后将这两个函数组合为一个函数?

第一个函数,它比较事务数组上的属性credit

  public filterByCredit(filter: string) {

    switch (filter) {
      case 'Non-blanks':
        this.filteredTxs = this.localTransactions.filter(tx => tx.credit);
        break;
      case 'Blanks':
        this.filteredTxs = this.localTransactions.filter(tx => !tx.credit);
        break;
      case '> 500':
        this.filteredTxs = this.localTransactions.filter(tx => tx.credit > 500);
        break;
    }

  }

比较属性debit的第二个函数

public filterByDebit(filter: string) {
    switch (filter) {
      case 'Non-blanks':
        this.filteredTxs = this.localTransactions.filter(tx => tx.debit);
        break;
      case 'Blanks':
        this.filteredTxs = this.localTransactions.filter(tx => !tx.debit);
        break;
      case '> 500':
        this.filteredTxs = this.localTransactions.filter(tx => tx.debit > 500);
        break;
    }

3 个答案:

答案 0 :(得分:3)

您可以传递key参数并将其用作对象属性的访问器。

public filterByDebit(filter: string, key: string) {
    switch (filter) {
        case 'Non-blanks':
            this.filteredTxs = this.localTransactions.filter(tx => tx[key]);
            break;
        case 'Blanks':
            this.filteredTxs = this.localTransactions.filter(tx => !tx[key]);
            break;
        case '> 500':
            this.filteredTxs = this.localTransactions.filter(tx => tx[key] > 500);
            break;
    }
}

答案 1 :(得分:1)

只需发送另一个参数:

public filterByCredetDebit(filter, creditOrDebit) {
    switch (filter) {
        case 'Non-blanks':
            this.filteredTxs = this.localTransactions.filter(tx => tx[creditOrDebit]);
            break;
        case 'Blanks':
            this.filteredTxs = this.localTransactions.filter(tx => !tx[creditOrDebit]);
            break;
        case '> 500':
            this.filteredTxs = this.localTransactions.filter(tx => tx[creditOrDebit] > 500);
            break;
    }
}

答案 2 :(得分:1)

您可以尝试这样。 向接受creditdebit类型的函数中再添加一个参数。然后在函数集中设置一个变量,取决于贷方或借方

public filterByType(filter: string,type:string) {
  let __tp
  if(type==='credit'){
    __tp='credit'
  }
  else{
    __tp='debit'
  }
    switch (filter) {
      case 'Non-blanks':
        this.filteredTxs = this.localTransactions.filter(tx => tx[__tp]);
        break;
      case 'Blanks':
        this.filteredTxs = this.localTransactions.filter(tx => !tx[__tp]);
        break;
      case '> 500':
        this.filteredTxs = this.localTransactions.filter(tx => tx[__tp] > 500);
        break;
    }
}