[英]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.