In my Java to Typescript data transfer, I am encountering an issue with objects containing "Map" properties. To define my Typescript models, I use interfaces instead of classes:
export interface Foo {
bar: Map<string, Bar>;
mapOfBar: Map<string, Map<string, Bar>>;
}
export interface Bar {
someField: string;
}
To handle the JSON object and convert it to type Foo, I implemented the following code:
import {HttpClient} from '@angular/common/http';
...
export class FooService {
constructor(private http: HttpClient) {
}
getFoo(): Observable<Foo> {
return this.http.get<Foo>('/some/route/to/FooEndpoint');
}
}
The issue arises when bar
and mapOfBar
are returned as type object instead of Map
. After extensive research, I came up with a solution by modifying my conversion logic as follows:
getFoo(): Observable<Foo> {
return this.http
.get<Foo>('/some/route/to/FooEndpoint')
.pipe(
map((res: Foo) => {
res.bar = new Map(Object.entries(res.bar));
let actualMapOfBar = new Map(Object.entries(res.mapOfBar));
res.mapOfBar = new Map();
for (let [key, bar] of actualMapOfBar) {
res.mapOfBar.set(key, new Map(Object.entries(bar)));
}
return res;
})
);
}
Although this approach successfully returns bar
and mapOfBar
as Maps, it feels inefficient and cumbersome.
As someone who pays attention to detail, I find this method clunky and not ideal for deeply nested object structures.
Are there better ways to tackle this issue? Is there a more efficient or automated method to leverage Typescript interfaces for object conversion?
(Using Angular 9.1, Typescript 3.8, rxjs 6.5)
EDIT: Here is an example response from the endpoint:
{"bar":{"key1":{"someField":"A"},"key2":{"someField":"B"},"key3":{"someField":"C"}},"mapOfBar":{"A":{"key1":{"someField":"A"},"key2":{"someField":"B"},"key3":{"someField":"C"}},"B":{"key1":{"someField":"A"},"key2":{"someField":"B"},"key3":{"someField":"C"}},"C":{"key1":{"someField":"A"},"key2":{"someField":"B"},"key3":{"someField":"C"}}}}