[英]Map JSON object into TypeScript Object
I am returning an array of objects from server using AJAX JQuery, an example 我正在使用AJAX JQuery从服务器返回对象数组
[{"Name":"Name1","ResultSet":[{"Id": 1,"Name":"Name1"}, {"Id": 2,"Name":"Name2"}]},{"Name": "Name11", "ResultSet": [{"Id": 11, "Name": "Name11"}, {"Id": 22, "Name": "Name22"}]}]
Also, I have the following TypeScript object I want to map 另外,我有以下要映射的TypeScript对象
interface IResult {
name: string;
resultSet: any;
}
export class Result implements IResult {
constructor(public name: string, public resultSet: any) { }
}
The way I am processing the results, 我处理结果的方式
dataService.execute(function (results) {
$(results).each(function (index, element) {
console.log(element.Name);
$.each(element.ResultSet, function (key, value) {
$.each(value, function (key, value) {
console.log(key + ' - ' + value);
});
});
});
});
Inside VS 2013, the compiler complains that: 在VS 2013中,编译器抱怨:
The property 'Name' does not exist on value of type 'Element'.
Is there a way to map the returned collection of objects to an array of TS Result objects? 有没有一种方法可以将返回的对象集合映射到TS Result对象的数组?
Thanks 谢谢
UPDATE I ended up looping as follows: 更新我最终循环如下:
var result = <Array<IResult>>results;
$.each(result, function (index, item) {
// item is Result instance
// item.name
console.log(item.name);
// item.resulSet
$.each(item.resultSet, function (key, val) {
// val is single Object (one result)
$.each(val, function (k, v) {
// k,v => key/value for each property on result
console.log(k + ' - ' + v);
});
});
}); });
In your interface definition for IResult the properties are lower case, but you try and access them using upper case. 在IResult的接口定义中,属性为小写字母,但您尝试使用大写字母访问它们。 Since your JSON has upper case change IResult to: 由于您的JSON具有大写字母,因此将IResult更改为:
interface IResult {
Name: string;
ResultSet: any;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.