Объект с несколькими свойствами - PullRequest
0 голосов
/ 26 февраля 2019

Я хочу вернуть объект с ключом date и 2 свойствами: margin и 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 возвращает объект с year в качестве ключа и 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'из неопределенного

Ответы [ 2 ]

0 голосов
/ 26 февраля 2019

Сначала необходимо определить 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
}
0 голосов
/ 26 февраля 2019

Возьмите эту часть кода

if (!(moment(timesheet.date).format('YYYY') in this.grossMargin))

Хорошо, давайте назовем момент (timesheet.date) .format ('YYYY') ключом.Вы проверяете if! (Введите this.grossMargin), затем пытаетесь установить поле для неопределенного объекта, выполняя this.grossMargin [key] .margin.Если вы хотите инициализировать объект, вы должны сделать

this.grossMargin[key] = { 
  margin: value, 
  consultant: value 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...