I am returning an array of objects from server using AJAX JQuery, an example
[{"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
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:
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?
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. Since your JSON has upper case change IResult to:
interface IResult {
Name: string;
ResultSet: any;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.