Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map JSON to TypeScript objects with calculated properties

I have a fairly standard service returning some JSON.

An example return body could be:

[{ a: 1, b: 2 }]

I want to map this to instances of the following Typescript class:

export class MyClass {
  a: number;
  b: number;

  get c() : number {
      return this.a + this.b;
  }
}

I incorrectly assumed HttpClient.get would do exactly this, but while it does map it to compatible objects, they are missing the property.

this.http.get<MyClass[]>('http://www.example.com/endpoint');

Is there a way to get Angular to do this automatically, or do I need to a manual mapping like this:

.map(data => {
    const results : MyClass[];
    for(const d of data) {
        const mc = new MyClass();
        mc.a = d.a;
        mc.b = d.b;
        results.push(mc);
    }
    return results;
});

It works, but it is tedious code to write and can easily create dependencies I do not want in my code.

like image 728
Troels Larsen Avatar asked Feb 22 '26 18:02

Troels Larsen


1 Answers

1) You can create some parse function like

const mapJsonToObject = Type => obj => Object.assign( new Type(), obj );

And use it like

...
.map( data => mapJsonToObject(MyClass) )
...

2) In other way, you can assign all properties in class constructor

export class MyClass {
  a: number;
  b: number;

  constructor(obj: MyClass) {
    Object.assign( this, obj );
  }

  get c() : number {
      return this.a + this.b;
  }
}

And in map simply create new entity of MyClass

...
.map( data => new MyClass( data as MyClass ) )
...
like image 147
Mixalloff Avatar answered Feb 25 '26 15:02

Mixalloff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!