Home > Software design >  Use Array.prototype.map() to change property of an object in an array
Use Array.prototype.map() to change property of an object in an array

Time:02-18

I work for a project and I cannot solve the following issue...

The goal is to translate the "resourceKeys" properties and sort them alphabetically.

In order for that, each single property from an array of objects must be translated individually.

The code:

const self = this;

    self._translateService.onLangChange.subscribe(() => {

      self.absenceTypes = self.absenceTypes.map((x) => self._translateService.instant(x.resourceKey));
      self.absenceTypes.sort((a, b) => a.resourceKey.localeCompare(b.resourceKey));
      
      console.log(self.absenceTypes);
    })

The source:

export const absenceTypes: ISelectItem[] = [
    { key: AbsenceType.Sickness, resourceKey: "AbsenceTypeSickness" },
    { key: AbsenceType.ParentalLeave, resourceKey: "AbsenceTypeParentalLeave" },
    { key: AbsenceType.ChildCare, resourceKey: "AbsenceTypeChildCare" },
    { key: AbsenceType.Vacation, resourceKey: "AbsenceTypeVacation" },
    { key: AbsenceType.LeaveOfAbsence, resourceKey: "AbsenceTypeLeaveOfAbsence" },
    { key: AbsenceType.UnpaidVacation, resourceKey: "AbsenceTypeUnpaidVacation" }
]

I want the console to show something like this this: { key: AbsenceType.Sickness, resourceKey: Sickness }

Instead from map((x) => self._translateService.instant(x.resourceKey)); I only get :0: Sickness from the console.

Is there a way in which I can retain the key of the object whilst changing (translating) the resourceKey?

CodePudding user response:

Use the spread (...) operator to supplement the original object with the updated resourceKey:

map((x) => ({
    ...x, 
    resourceKey: self._translateService.instant(x.resourceKey)) 
  }));

  • Related