Jason Swett Jason Swett - 17 days ago 5
TypeScript Question

Instantiating a TypeScript class from a JSON array

This question is maybe not 100% original but the questions/answers I've found so far seem to neglect a certain elephant in the room.

I have a situation which I'll simplify for example's sake. Let's say I have the following JSON response:

[
{
"place": {
"name": "The Cottage",
"rating": 4
}
},
{
"place": {
"name": "El Burrito Loco",
"rating": 5
}
}
]


Then let's say I want to have a Typescript class called
Place
. If I instantiate each element as a
Place
, I have this stupid situation:

<!-- this is an Angular template -->

<ul>
<li *ngFor="let place of places">{{ place.place.name }}</li>
</ul>


What I would prefer, of course, is
{{ place.name }}
rather than
{{ place.place.name }}
.

So my question is: how can I transform a JSON response to match my data model?

I've already seen questions/answers like this one.

What confuses me is that a) I imagine that this transformation desire is an incredibly common one, and b) all the answers I've found so far seem to involve a ton of hacky boilerplate (no offense).

So what's the deal, does everybody just copy and paste all this boilerplate into their apps to meet what must be a very common need, and the TypeScript (or Angular) developers just didn't come up with a way to meet this need with the language or framework? That doesn't seem likely. It's very confusing.

Any insight is very much appreciated.

Answer

Here's what I ended up doing. Thanks to Pankaj Parkar for providing some clues that led me here.

  getList(): Observable<Place[]> {
    return this.http.get(this.placesUrl)
               .map(response => response.json().data)
               .map(data => data.map((item) => {
                 return <Place>({
                   name: item.place.name,
                   place: item.place
                 });
               }));
  }