[英]Typescript: Convert JSON object to a class/interface object
我试图将API响应转换为typescript类/接口。
这里API返回一个具有一些属性的对象列表,但我只需要几个响应对象的属性。
API响应示例:
[{ 'Id' : 1, 'Name': 'test', 'Description: 'Test', 'PropertyX': 'x', 'PropertyY' : 'y' }, ...]
打字稿类
Class Response { Id: string; Name: string; }
能否请您建议将JSON对象转换为打字稿对象的最佳方法。
我建议创建一个界面来描述您在应用中使用的属性,并忽略其余的:
所以假设您的回答如下:
const response = [{
'Id' : 1,
'Name': 'test',
'Description: 'Test',
'PropertyX': 'x',
'PropertyY' : 'y'
}, {
'Id' : 2,
'Name': 'test2',
'Description: 'Test2',
'PropertyX': 'x2',
'PropertyY' : 'y2'
}
];
而你只对Id
和Name
感兴趣,只需创建一个这样的界面:
interface IMyObject {
Id: String;
Name: String;
}
然后在你的应用程序的其余部分,您可以将响应转换为IMyObject[]
例如,如果函数使用您的响应:
function myFunction(response: IMyObject[]) { ... }
或者如果您需要返回该类型,您可以像这样进行直接投射:
return response as MyObject[];
编辑:如下面的评论所述,只是将您的对象转换为IMyObject
不会删除您不感兴趣的额外属性。
为此,请使用.map
:
const formattedResponse: IMyObject = reponse.map(item => {
Id: item.Id,
Name: item.Name
});
您可以使用forEach方法并使用所需的属性创建新对象。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.