Reputation: 1091
I want to return an object with key the date, and 2 properties: margin and consultant.
!(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 returns an object with year as key and grossMargin as value. Now I want to add another element in the object like the total of the consultant.
I tried this but this doesn't work:
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
}
Error: Cannot set property 'margin' of undefined
Upvotes: 0
Views: 59
Reputation: 1396
You need to first define this.grossMargin['2018'] (for example).
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
}
Upvotes: 2
Reputation: 2499
Take this part of the code
if (!(moment(timesheet.date).format('YYYY') in this.grossMargin))
Ok, let's call moment(timesheet.date).format('YYYY') the key. You're checking if !(key in this.grossMargin) then you try to set the margin for an undefined object, by doing this.grossMargin[key].margin. If you want to initialize the object you should do
this.grossMargin[key] = {
margin: value,
consultant: value
}
Upvotes: 1