有谁知道优化我的代码的更好方法?

时间:2019-03-29 19:10:42

标签: javascript optimization logic

我有一个对象activeRow,它的参数为prevValueeditedValue

我使用companyDataKeys作为默认键。因此,如果logDetailsArray

,我需要将对象logDetails推入数组prevValue[key] !== editedValue[key]

如果logDetailsprevValueeditedValue,我也推undefined,这意味着它没有价值或不存在

const prevValues = this.state.activeRow.prevValue
const editedValues = this.state.activeRow.editedValue

Object.keys(this.state.companyDataKeys).forEach((key) => {
  if (prevValues === undefined) {
    logDetails = {
      param: companyDataValue[key],
      prevValue: '',
      editedValue: (editedValues[key] === undefined) ? '' : editedValues[key].toString(),
    }
    logDetailsArray.push(logDetails)
  }
  if (editedValues === undefined) {
    logDetails = {
      param: companyDataValue[key],
      prevValue: (prevValues[key] === undefined) ? '' : prevValues[key].toString(),
      editedValue: '',
    }
    logDetailsArray.push(logDetails)
  }
  if (editedValues !== undefined && prevValues !== undefined) {
    if (prevValues.hasOwnProperty(key) && editedValues.hasOwnProperty(key)) {
      if (editedValues[key] !== prevValues[key]) {
        logDetails = {
          param: companyDataValue[key],
          prevValue: prevValues[key].toString(),
          editedValue: editedValues[key].toString(),
        }
        logDetailsArray.push(logDetails)
      }
    } else if (prevValues[key] !== undefined && editedValues[key] !== undefined) {
      logDetails = {
        param: companyDataValue[key],
        prevValue: (prevValues[key] !== undefined) ? prevValues[key].toString() : '',
        editedValue: (editedValues[key] !== undefined) ? editedValues[key].toString() : '',
      }
      logDetailsArray.push(logDetails)
    }
  }
});

1 个答案:

答案 0 :(得分:1)

我想,这就是您想要的!

通过使用javascript的{​​{3}}行为和OR逻辑,我们将您的长代码简化为更简单的代码!

const prevValues = this.state.activeRow.prevValue || {};
const editedValues = this.state.activeRow.editedValue || {};

Object.keys(this.state.companyDataKeys).forEach((key) => {
    logDetails = {
        param: companyDataValue[key],
        prevValue: (prevValues[key] || '').toString(),
        editedValue: (editedValues[key] || '').toString(),
    };
    logDetailsArray.push(logDetails);
});

希望,这会对您有所帮助。谢谢!