我目前正在尝试基于我从ajax调用获得的json创建一个对象。它看起来像这样:
{
"users": [
{
"address": {
"city": "testCity",
"houseNumber": 69,
"id": 1,
"postcode": 420,
"street": "testStreet"
},
"email": "testEmail@test.de",
"gender": "male",
"id": 3,
"isAdmin": false,
"lastname": "testLastname",
"prename": "testPrename",
"projects": [
{
"archived": null,
"files": [],
"id": 1,
"name": "testProject",
"timestamp": "2017-01-27T20:23:06+00:00",
"uri": "http://localhost:2000/api/projects/1"
}
],
"uri": "http://localhost:2000/api/users/3"
}
]
}
我在User类中定义了一个静态方法,用于从该输入创建User类型的对象。我正在寻找的是一种创建类Project和Address的对象的方法,并将它们设置为User Class中的相应字段。这就是我目前所拥有的:
export class User {
public uri: string = undefined;
public id: number = undefined;
public readonly isAdmin: boolean = undefined;
public prename: string = undefined;
public lastname: string = undefined;
public gender: string = undefined;
public email: string = undefined;
private password: string = undefined;
public address: Address = undefined;
public projects: Project[] = undefined;
constructor() {
}
// Returns an array containing one or more User objects
public static load(res: Response): User[]{
let data: Object = res.json();
let users: User[] = [];
// Payload contains multiple Users (array)
if(data.hasOwnProperty('users')){
let dataUsers: Object[] = data['users'];
for(let dataUser of dataUsers){
let user = new User();
for(let key in user){
if(dataUser.hasOwnProperty(key)){
if(typeof dataUser[key] === 'object'){
// If it's an object, find the class that matches the 'content' of the object and call their load method
}
} else {
user[key] = dataUser[key];
}
}
}
users.push(user);
}
// Payload contains a single User
} else if(data.hasOwnProperty('user')){
let dataUser = data['user'];
let user = new User();
for(let key in user){
if(data.hasOwnProperty(key)){
user[key] = dataUser[key];
}
}
users.push(user);
} else {
users.push(new User());
}
return users;
}
一种方法是通过检查密钥是“项目”还是“地址”来硬编码地址和项目的对象创建,但我正在寻找一种更“动态”的方式来点缀它。
答案 0 :(得分:0)
您可以将加载函数存储在地图中。它看起来像这样。
class Address {
static load(data:Object) {
//...
}
}
class Project {
static load(data:Object) {
}
}
let keyClassMap : { [id:string]: (data:Object) => any } = {
address: Address.load,
project: Project.load,
}
此对象的键是与您感兴趣的类定义相对应的键。
然后在你的陈述中你可以做到:
if(typeof dataUser[key] === 'object'){
user[key] = keyClassMap[key](dataUser[key]);
}