我想返回一个带有日期键和2个属性的对象:保证金和顾问。
!(moment(timesheet.date).format('YYYY') in this.grossMargin) ?
this.grossMargin[moment(timesheet.date).format('YYYY')] = timesheet.invoice.total - timesheet.purchase.total :
this.grossMargin[moment(timesheet.date).format('YYYY')] += timesheet.invoice.total - timesheet.purchase.total
this.grossMargin返回一个对象,其中年份作为键,grossMargin作为值。现在,我想在对象中添加另一个元素,例如顾问的总数。
我尝试了这个,但这不起作用:
if (!(moment(timesheet.date).format('YYYY') in this.grossMargin)) {
this.grossMargin[moment(timesheet.date).format('YYYY')].margin = timesheet.invoice.total - timesheet.purchase.total
this.grossMargin[moment(timesheet.date).format('YYYY')].consultant = consultant.invoice.total - consultant.purchase.total
} else {
this.grossMargin[moment(timesheet.date).format('YYYY')].margin += timesheet.invoice.total - timesheet.purchase.total
this.grossMargin[moment(timesheet.date).format('YYYY')].consultant += consultant.invoice.total - consultant.purchase.total
}
错误:无法设置未定义的属性'margin'
答案 0 :(得分:2)
您需要首先定义this.grossMargin ['2018'](例如)。
if (!(moment(timesheet.date).format('YYYY') in this.grossMargin)) {
this.grossMargin[moment(timesheet.date).format('YYYY')] = {};
this.grossMargin[moment(timesheet.date).format('YYYY')].margin = timesheet.invoice.total - timesheet.purchase.total
this.grossMargin[moment(timesheet.date).format('YYYY')].consultant = consultant.invoice.total - consultant.purchase.total
} else {
// here this.grossMargin[moment(timesheet.date).format('YYYY')] is defined,
// but you need to make sure it's an object first
this.grossMargin[moment(timesheet.date).format('YYYY')].margin += timesheet.invoice.total - timesheet.purchase.total
this.grossMargin[moment(timesheet.date).format('YYYY')].consultant += consultant.invoice.total - consultant.purchase.total
}
答案 1 :(得分:1)
采用这部分代码
if (!(moment(timesheet.date).format('YYYY') in this.grossMargin))
好吧,让我们将moment(timesheet.date).format('YYYY')称为键。您正在检查!(this.grossMargin中的键),然后尝试通过执行this.grossMargin [key] .margin来设置未定义对象的边距。如果要初始化对象, 应该做
this.grossMargin[key] = {
margin: value,
consultant: value
}