使用Javascript

时间:2018-07-04 10:46:41

标签: javascript

我想在JavaScript filter()方法中动态添加条件。

我有以下代码:

let condition = '';
let a = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];

if (this.selectedEmployeeAlias != undefined) {
  condition += '&& a => a.empEmail === this.selectedEmployeeAlias';
}
if (this.employeeStatusList != undefined) {
  condition += '&& a.employeeAction === this.employeeStatusList'
}
if (this.selectedTransactionNo != undefined) {
  condition += '&& a.transactionNo === this.selectedTransactionNo';
}
if (this.selectedDeviceList != undefined) {
  condition += ' && a.deviceListName == this.selectedDeviceList';
}
if (this.selectedProjectName != undefined) {
  condition += '&& a.projectName == this.selectedProjectName';
}

var finalCondition = condition.substring(2, condition.length);
var fArray = arrayDetails.filter(finalCondition);

代码返回错误为:

  

finalCondition不是函数。

能否让我知道如何动态向filter()添加条件。

3 个答案:

答案 0 :(得分:2)

您可以带条件的函数数组。然后使用every进行迭代。

var conditions = [];

if (this.selectedEmployeeAlias !== undefined) {
    conditions.push(a => a.empEmail === this.selectedEmployeeAlias);
}
if (this.employeeStatusList !== undefined) {
    conditions.push(a => a.employeeAction === this.employeeStatusList);
}
if (this.selectedTransactionNo !== undefined) {
    conditions.push(a => a.transactionNo === this.selectedTransactionNo);
}
if (this.selectedDeviceList !== undefined) {
    conditions.push(a => a.deviceListName == this.selectedDeviceList);
}
if (this.selectedProjectName !== undefined) {
    conditions.push(a => a.projectName == this.selectedProjectName);
}

var fArray = arrayDetails.filter(o => conditions.every(c => c(o)));

答案 1 :(得分:0)

当您获得按键的优劣时,只需将其循环并检查未定义的内容即可:

const keys = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];

const result = arrayDetails.filter(el => {
   for(const key of keys) {
     if(this[key] === undefined) continue;
     if(this[key] !== el[key]) return false;
   }
   return true;
});

答案 2 :(得分:-1)

eval进行救援!

虽然通常建议不要这样做,但是eval确实可以满足您的要求。

只需在condition方法内将eval变量传递给.filter,瞧!

let condition='';
let a = ['empEmail', 'employeeAction', 'transactionNo', 'deviceListName', 'projectName'];

if (this.selectedEmployeeAlias != undefined) {                    
  condition += '&& a => a.empEmail === this.selectedEmployeeAlias';
}
if (this.employeeStatusList != undefined) {
  condition += '&& a.employeeAction === this.employeeStatusList'
}
if (this.selectedTransactionNo != undefined) {
  condition += '&& a.transactionNo === this.selectedTransactionNo';
}
if (this.selectedDeviceList != undefined) {
  condition += ' && a.deviceListName == this.selectedDeviceList';
}
if (this.selectedProjectName != undefined) {
  condition += '&& a.projectName == this.selectedProjectName';
}

var finalCondition=condition.substring(2, condition.length);
var fArray=arrayDetails.filter(stuff => eval(finalCondition));