I have an json result which has nested objects. I need to cast them to my custom objects which have different property names than the json result.
For the parent object(Vraag) I can map them. But for the sub objects(Antwoord) I couldn't.
Json
{
"question":"Vraag 1",
"answers":[
{
"answer":"Voetbal"
},
{
"answer":"Volleybal"
}
]
}
My Objects
export class Vraag {
tekst?: string;
antwoorden?: Antwoord[];
constructor(tekst?: string, antwoorden?: Antwoord[]) {
this.tekst = tekst;
this.antwoorden = antwoorden;
}
}
export class Antwoord {
tekst?: string;
constructor(tekst?: string) {
this.tekst = tekst;
}
}
Service
get(): Observable<Vraag> {
return this.http.get('the json above')
.map((response: Response) => response.json())
.map(({question , answers}) => new Vraag(question , answers)); // answers needs to be fetched inside the object too
}
So, how can I map the json like this?:
new Vraag("Vraag 1" , [new Antwoord("voetbal"),new Antwoord("volleybal")]);
answers.map(answer => new Answer(answer))?new Vraag(question , answers)asnew Vraag(question , answers.map(({answer}) => new Antwoord(answer)))so thatanswers(Antwoord)can have multiple different named properties. your comment helped me to get on the right path.error TS2345: Argument of type 'string' is not assignable to parameter of type 'Antwoord[]'.