How to map a subset of an API result to a class in an Angular project

1569 views angular

I have an Angular 6 project and am not sure how to map API results to a class

I have an API that returns results like the following

    "Id": "f400b615-9041-4e64-a7d1-ff04855b2d00",
    "fields": [
            "cid": "auth0|5b3b0031297c9026b864fc6e",
            "name": "Field1",
            "questionText": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            "cid": "auth0|5b3b0031297c9026b864fc6e",
            "name": "Field2",
            "questionText": "Ut enim ad minim veniam, quis nostrud exercitation ullamco",
        // etc

There are up to 100 fields, and I'd like to generate a class from each of them.

I have the following class definition:

export class OpportunityField {
    fieldId = ""
    name = ""
    questionText = ""

How do I parse my API to get the fields related to 'Field2' and make that a new object that I can then pass to another function?

answered question

1 Answer


Your actualy Interface should look like this, you can check with JSON2TS

export interface Field {
    cid: string;
    name: string;
    questionText: string;

export interface OpportunityField {
    Id: string;
    fields: Field[];

now you can access fields to using OpportunityField.fields[1].

posted this

Have an answer?


Please login first before posting an answer.