Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Convert JSON object to a class/interface object

I m trying to convert an API response to typescript class/interface.

Here the API returns a list of objects with some properties, but I need only few of the properties of the response object.

API Response Example:

    [{
    'Id' : 1,
    'Name': 'test',
    'Description: 'Test',
    'PropertyX': 'x',
    'PropertyY' : 'y'
    },
    ...]

Typescript Class


    Class Response {
     Id: string;
     Name: string;
    }

Can you please suggest me what will be the best approach for converting the JSON object to a typescript object.

like image 391
Nitin Avatar asked Apr 30 '18 04:04

Nitin


2 Answers

I would suggest creating an interface that describes the properties you are using in your app and ignore the rest:

So assuming your response looks like:

const response = [{
      'Id' : 1,
      'Name': 'test',
      'Description': 'Test',
      'PropertyX': 'x',
      'PropertyY' : 'y'
    }, {
      'Id' : 2,
      'Name': 'test2',
      'Description': 'Test2',
      'PropertyX': 'x2',
      'PropertyY' : 'y2'
    }
];

and you are only interested in Id and Name, just create an interface like so:

interface IMyObject {
  Id: String;
  Name: String;
}

then in the rest of your app you can cast the response to IMyObject[]

For example if a function uses your response:

function myFunction(response: IMyObject[]) { ... }

or if you need to return that type, you can do a direct cast like so:

return response as MyObject[];

EDIT: As mentioned in the comment below, simply casting your object to IMyObject does not remove the extra properties you are not interested in.

To do so, use .map:

const formattedResponse: IMyObject = reponse.map(item => {
  Id: item.Id,
  Name: item.Name
});
like image 65
klugjo Avatar answered Oct 24 '22 00:10

klugjo


You can use forEach method and create a new object with the properties you require.

myarray=[];
 ngOnInit() {
     this.myvalues();

  }


    myMethod()
        {
           const response = [{
            'Id' : 1,
            'Name': 'test',
            'Description': 'Test',
            'PropertyX': 'x',
            'PropertyY' : 'y'
          }, {
            'Id' : 2,
            'Name': 'test2',
            'Description': 'Test2',
            'PropertyX': 'x2',
            'PropertyY' : 'y2'
          }
        ];

        response.forEach(value=>{
         this.myarray.push(
               {
                'ID':value.Id,
               'Name':value.Name
              }
            )
        });
        console.log(this.myarray);

WORKING DEMO

like image 32
Vikas Avatar answered Oct 23 '22 23:10

Vikas