使用数组索引变量而不是硬编码值

时间:2019-10-28 18:58:08

标签: javascript arrays

我有以下方法,我想使用前三行中声明的三个变量,而不是使用for循环检查硬编码值并将其添加到res。我正在尝试遵循,以便只需要更改successStates和failedStates内部的值

//    if(successStates.find(x => x === filterVal)){
//         filter1 = successStates[0];
//         filter2 = successStates[1];
//    } 

getJobFilter() {
  let successStates = ['ACCEPTED_STATE', 'ACTIVE_STATE'];
  let failedStates = ['INACTIVE_STATE'];
  let otherStates = ['UNKNOWN'];
  let res = [];
  let filter =
    JSON.parse(sessionStorage.getItem('cdgFilter') || '{}');
  for (let key in filter) {
    if (key) {
      if (key === 'collection_status') {
        let filterVal: any;
        let filter1, filter2;

        if (filterVal === "SUCCESSFUL") {
          filter1 = 'ACTIVE_STATE';
          filter2 = 'ACCEPTED_STATE';
        } else if (filterVal === "FAILED") {
          filter1 = 'UNKNOWN_STATE';
          filter2 = 'INACTIVE_STATE';
        }
        res.push({
          'field': 'State',
          'value': filter1
        }, {
          'field': 'State',
          'value': filter2
        });
      } else {
        res.push({
          'field': key,
          'value': filter[key].filter
        });
      }
    }
  }
  return res;
}

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用地图对象:

const collectionStatusFilters = {
  SUCCESSFUL: ['ACTIVE_STATE', 'ACCEPTED_STATE'],
  FAILED: ['UNKNOWN_STATE', 'INACTIVE_STATE']
}

然后您可以这样替换if语句:

const filters = collectionStatusFilters[filterVal];
res = res.concat(
  filters.map(filter => ({
    field: 'State',
    value: filter
  }))
);