我使用AJAX JQuery从服务器返回一个对象数组,一个例子
[{"Name":"Name1","ResultSet":[{"Id": 1,"Name":"Name1"}, {"Id": 2,"Name":"Name2"}]},{"Name": "Name11", "ResultSet": [{"Id": 11, "Name": "Name11"}, {"Id": 22, "Name": "Name22"}]}]
另外,我有以下要映射的TypeScript对象
interface IResult {
name: string;
resultSet: any;
}
export class Result implements IResult {
constructor(public name: string, public resultSet: any) { }
}
我处理结果的方式,
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);
});
});
});
});
在VS 2013中,编译器抱怨:
The property 'Name' does not exist on value of type 'Element'.
有没有办法将返回的对象集合映射到TS Result对象数组?
由于
更新 我最终循环如下:
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);
});
});
});
答案 0 :(得分:3)
在IResult的接口定义中,属性是小写的,但您尝试使用大写访问它们。由于您的JSON具有大写更改IResult:
interface IResult {
Name: string;
ResultSet: any;
}