0

I have the following class:

export class DailyEntry {
  date: Moment;
  breaks: Duration;
  startTime: Moment;
  endTime: Moment;
  project: Project;
  employee: Employee;
  workplace: string;
  performanceRecord: string;
  duration?: Duration;
  status;
  _links?: Link;

  constructor(date: string, breaks: string, startTime: string, endTime: string, workplace: string, performanceRecord: string,
              status: string, _links: Link, employee?: Employee) {
    this.date = moment(date);
    this.breaks = moment.duration(breaks);
    this.startTime = moment(date + 'T' + startTime);
    this.endTime = moment(date + 'T' + endTime);
    this.duration = moment.duration(this.endTime.diff(this.startTime)).subtract(this.breaks);
    this.workplace = workplace;
    this.performanceRecord = performanceRecord;
    this.status = STATUS[status];
    this._links = _links;
    this.employee = employee;
  }
}

I have an API-request in my customerService which maps the response to an array of DailyEntry:

search(searchUrl: string, params: HttpParams): Observable<DailyEntry[]> {
    return this.http.get<Data>(BASE_URL + 'search/' + searchUrl, this.authService.setHeadersWithParams('application/json', params))
      .pipe(
        map(function (data) {
          const entries: DailyEntry[] = [];
          data.forEach(function (e) {
            entries.push(new DailyEntry(e.date, e.breaks, e.startTime, e.endTime, e.workplace, e.performanceRecord, e.status, e._links, e.employee));
          });
          return entries;
        }),
        catchError(this.handleService.error)
      );
  }

In my customerComponent i have the following set defined:

employeesSet: Set<Employee> = new Set();

And inside that method, i call the search method the following way:

const dailyEntriesObservable = this.dailyEntryService.search('findByProjectId', httpParams);
          dailyEntriesObservable.subscribe(dailyEntries => {
            dailyEntries.forEach(dailyEntry => {
              this.employeesSet.add(dailyEntry.employee);
            });
          });

So i expected only unique employees being added to the set. But the set contains the same employee several times. But i guess they only have same values, but arent actually the same objects so they are still added in the set? How could i fix that?

M.Dietz
  • 710
  • 5
  • 13
  • 1
    Yeah, it uses object reference equality. Don't use a `Set` for this... presumably an `Employee` has some unique identifier... use a plain object whose keys are that identifier and whose values are the corresponding `Employee` object. Then you just lookup by key – jcalz Nov 13 '19 at 17:27
  • 1
    Possible duplicate of [How to customize object equality for JavaScript Set](https://stackoverflow.com/questions/29759480/how-to-customize-object-equality-for-javascript-set) – jcalz Nov 13 '19 at 17:31

0 Answers0