后台返回的数据格式有如下几种
第一种一般是code:name
形式返回,例如
response:{
"langs": {
"en_gb": "English (UK)",
"zh_hk": "Traditional Chinese (Hong Kong)",
"zh_cn": "Simplified Chinese (China)"
}
}
前端的数据需要构造出以下
data:{
languages:[{
code:"en_gb",
name:"English (UK)"
},{
code:"zh_hk",
name:"Traditional Chinese (Hong Kong)"
},{
code:"zh_cn",
name:"Simplified Chinese (China)"
}]
}
第二种是个对象的数组返回,例如
response:{
"countryList": [{
"key": "1",
"code": "AFG",
"name": "AFGHANISTAN",
"countryPhone": "93"
}, {
"key": "2",
"code": "ALA",
"name": "ALAND ISLANDS",
"countryPhone": "358"
}, {
"key": "3",
"code": "ALB",
"name": "ALBANIA",
"countryPhone": "355"
}]
}
前端需要对返回的response映射成如下
data:{
countryList:[{
countryCode: "AFG",
countryName: "AFGHANISTAN",
countryPrePhoneNumber: "93"
},{
countryCode: "ALA",
countryName: "ALAND ISLANDS",
countryPrePhoneNumber: "358"
},{
countryCode: "ALB",
countryName: "ALBANIA",
countryPrePhoneNumber: "355"
}]
}
上述过程基本都是遍历一个json来构造出另个json,可以写出一个通用的方法来做
以下是typsejs的写法
private popData<T extends Model>(respData: any , arr: Array<T>, t: T ,
fieldMap: any = {'keyField': 'code', 'valueField': 'name'}) {
if (!respData) return;
if (respData instanceof Array) {
respData.forEach(function (value) {
let item = Object.create(t);
for (let f in value) {
if (value[f] && fieldMap[f]) {
item[fieldMap[f]] = value[f];
}
}
arr.push(item);
});
} else {
for (let f in respData) {
if (respData.hasOwnProperty(f)) {
let item = Object.create(t);
item[fieldMap['keyField']] = f;
item[fieldMap['valueField']] = respData[f];
arr.push(item);
}
}
}
}
Model
export class Model {
code: string;
name: string;
}
Data
export class Data {
countryList ?: Array<Country> = new Array<Country>() ;
languages ?: Array<Language> = new Array<Language>() ;
}
Country和Language
export class Country extends Model {
countryCode: string;
countryName: string;
countryPrePhoneNumber: string;
}
export class Language extends Model {
}
针对第一种
let initData = new Data();
this.popData(response['langs'], initData.languages, new Language());
针对第二种
let initData = new Data();
this.popData(response['countryList'], initData.countryList, new Country(),
{'code': 'countryCode',
'name': 'countryName',
'countryPhone': 'countryPrePhoneNumber' });
针对第一种的另种情况,Language虽然继承Model,但是命名不想用code和name而是
export class Language extends Model {
langCode : string;
langName :string;
}
可以使用如下
let initData = new Data();
this.popData(response['langs'], initData.languages, new Language(),
{'keyField': 'langCode', 'valueField': 'langName'});