Search code examples
angulartypescriptrxjsclass-transformer

Map json array to typescript object array with constructor


So I have a json array like this:

[
  {
    "title": "This is the first title",
    "image": "img/first_img.png"
  },
  {
    "title": "This one is the second",
    "image": "img/second_img.png"
  }
]

My goal is to map the simple json array to typescript object array, which is defined as follows.

export class GenericField {
  public Required: boolean;
  public Disabled: boolean;

  constructor() {
    this.Required = false;
    this.Disabled = false;
  }
}

export class StringField extends GenericField {
  private readonly _minLength: number | null;
  private readonly _maxLength: number | null;
  private readonly _value: string;

  constructor(
    minLength: number | null,
    maxLength: number | null,
    value: string
  ) {
    super();
    this._minLength = minLength;
    this._maxLength = maxLength;
    this._value = value;
  }
// ...
}

export class UrlField extends GenericField {
  private _url: string;

  constructor(url: string) {
    super();
    this._url = url;
  }

  public get Url(): string {
    return this._url;
  }
}

export class SliderObject {
  public title: StringField;
  public image: UrlField;

  constructor(title: string, image: string) {
    this.title = new StringField(null, null, title);
    this.image = new UrlField(image);
    this.image.Disabled = true;
  }
}

When I map with class-transformer, the objects aren't mapped correctly. How do I achieve that I can access Required field and Disabled field, which is not present in json.

Stackblitz

See my StackBlitz example here


Solution

  • It would be like the following (assuming response.data is where the JSON text is).

    const items: Array<{title: string, image: string}> = JSON.parse(response.data)
    
    const sliderObjects = items.map(item =>
        new SliderObject(item['title'], item['image']))