我有一个对象activeRow
,它的参数为prevValue
和editedValue
我使用companyDataKeys
作为默认键。因此,如果logDetailsArray
logDetails
推入数组prevValue[key] !== editedValue[key]
如果logDetails
或prevValue
为editedValue
,我也推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)
}
}
});
答案 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);
});
希望,这会对您有所帮助。谢谢!