0

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")]);

4
  • 5
    answers.map(answer => new Answer(answer))? Commented Jan 9, 2017 at 22:03
  • @jonrsharpe I've changed the new Vraag(question , answers) as new Vraag(question , answers.map(({answer}) => new Antwoord(answer))) so that answers(Antwoord) can have multiple different named properties. your comment helped me to get on the right path. Commented Jan 9, 2017 at 22:26
  • @jonrsharpe It gives now the following error: error TS2345: Argument of type 'string' is not assignable to parameter of type 'Antwoord[]'. Commented Jan 10, 2017 at 8:01
  • @jonrsharpe my bad, it's working now Commented Jan 10, 2017 at 10:02

1 Answer 1

2

You should just map answers array elements to required objects before passing it to Vraag constructor. Check the following snippet:

get(): Observable<Vraag> {
    return this.http.get('the json above')
                    .map((response: Response) => response.json())
                    .map(({question , answers}) => {
                        answers = answers.map(answer => new Antwoord(answer));
                        new Vraag(question , answers));
                    });
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.