Javascript / Typescript: new class instance inside Array.prototype.map function do not persist

477 Views Asked by At

I have the following class:

class Category {
  static ObjectMapToCategory(id: number, display: string, name: string): Category {
    return new Category(id, display, name);
  }

  constructor(private id: number, private display: string, private name: string) {
  }

  get Id(): number {
    return this.id;
  }

  get Display(): string {
    return this.display;
  }

  get Name(): string {
    return this.name;
  }
};

From an API endpoint I am getting an array of this other class:

class CategoryModel {
  constructor(public id: number, public display: string, public name: string) {
  }
}

Let's suppose I store the API response in:

let apiResponseArray:CategoryModel[];

The idea is to transform this array in another of type Category[]. For that I use the Array.prototype.map function:

let categoriesArray:Category[] = apiResponseArray.map(categoryModelElement => new Category(categoryModelElement.id, categoryModelElement.display, categoryModelElement.name));

Nevertheless, I end up with an array of objects containing only the properties: id, display and name. But properties (getters) Id, Display and Name from class Category, are lost. Any ideas why? Does it has anything to do with garbage collector deleting the new Category instance after returning from map? And thus, it is not taken as a class instance but as a plain object? That are my only thoughts...

Instead, if I do:

let categoriesArray:Category[] = [];
apiResponseArray.forEach(categoryModelElement => categoriesArray.push(new Category(element.id, element.display, element.name));

Then, it works. I get my array of Category elements.

Thanks in advance!

0

There are 0 best solutions below