以下是我的代码,其中我要根据特定的用户类型在对象的特定位置添加一个附加键。当前,我从字面上复制整个,然后将其传递给表。有没有一种更清洁的方式来做同样的事情?
代码-
myReportsHeader = () => {
const { valid_user } = this.props;
const { tableHeaders } = this.props.tableHeaders
const { labels: tableLabels } = tableHeaders
if (valid_user) {
return {
tb1: tableLabels.tb1,
tb2: tableLabels.tb2,
tb3: tableLabels.tb3,
tb4: tableLabels.tb4, // Add only if valid_user
tb5: tableLabels.tb5,
tb6: tableLabels.tb6,
tb7: tableLabels.tb7,
tb8: tableLabels.tb8,
tb9: tableLabels.tb9,
tb10: tableLabels.tb10
}
}
return {
tb1: tableLabels.tb1,
tb2: tableLabels.tb2,
tb3: tableLabels.tb3,
tb5: tableLabels.tb5,
tb6: tableLabels.tb6,
tb7: tableLabels.tb7,
tb8: tableLabels.tb8,
tb9: tableLabels.tb9,
tb10: tableLabels.tb10
}
}
最佳答案
只需删除无效用户必须排除的密钥:
myReportsHeader = () => {
const { valid_user } = this.props;
const { tableHeaders } = this.props.tableHeaders
const { labels: tableLabels } = tableHeaders
if (!valid_user) {
delete tableLabels['tb4']
}
return tableLabels
}
Delete operator