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.
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
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With