使用 TypeScript / Angular2 循环对象的 key/value
Loop over object's key/value using TypeScript / Angular2
如何使用 TypeScript 遍历对象并能够访问键和值?
我的 json 对象看起来像这样:
{
"clients": {
"123abc": {
"Forename": "Simon",
"Surname": "Sample"
},
"456def": {
"Forename": "Charlie",
"Surname": "Brown"
}
}
}
要填充的客户对象由如下所示的客户模型组成:
export class ClientModel {
id:string;
forename:string;
surname:string;
constructor(
private id:string,
private forename:string,
private surname:string
) {
this.id = id;
this.forename = forename;
this.surname = surname;
}
}
鉴于:
var a = {
"clients": {
"123abc": {
"Forename": "Simon",
"Surname": "Sample"
},
"456def": {
"Forename": "Charlie",
"Surname": "Brown"
}
}
};
class ClientModel {
constructor(
private id:string,
private forename:string,
private surname:string
) {}
}
以下是获取 ClientModel
对象数组的方法:
var clientList: ClientModel[] = Object.getOwnPropertyNames(a.clients)
.map((key: string) => new ClientModel(key, a.clients[key].Forename, a.clients[key].Surname));
...以及如何获取从 string
(id) 到 ClientModel
的地图:
var clientMap: { [key: string]: ClientModel } = Object.getOwnPropertyNames(a.clients)
.reduce((map: any, key: string) => {
map[key] = new ClientModel(key, a.clients[key].Forename, a.clients[key].Surname);
return map;
}, {});
经过 basarat 的评论并仔细查看 Object.keys()
,Object.keys
比 Object.getOwnPropertyNames()
更适合在这里使用。不同的是后者 returns 属性也是不可枚举的。它在这种特殊情况下没有实际区别,但应该使代码的意图更加明确。其他一切都保持不变。
如何使用 TypeScript 遍历对象并能够访问键和值?
我的 json 对象看起来像这样:
{
"clients": {
"123abc": {
"Forename": "Simon",
"Surname": "Sample"
},
"456def": {
"Forename": "Charlie",
"Surname": "Brown"
}
}
}
要填充的客户对象由如下所示的客户模型组成:
export class ClientModel {
id:string;
forename:string;
surname:string;
constructor(
private id:string,
private forename:string,
private surname:string
) {
this.id = id;
this.forename = forename;
this.surname = surname;
}
}
鉴于:
var a = {
"clients": {
"123abc": {
"Forename": "Simon",
"Surname": "Sample"
},
"456def": {
"Forename": "Charlie",
"Surname": "Brown"
}
}
};
class ClientModel {
constructor(
private id:string,
private forename:string,
private surname:string
) {}
}
以下是获取 ClientModel
对象数组的方法:
var clientList: ClientModel[] = Object.getOwnPropertyNames(a.clients)
.map((key: string) => new ClientModel(key, a.clients[key].Forename, a.clients[key].Surname));
...以及如何获取从 string
(id) 到 ClientModel
的地图:
var clientMap: { [key: string]: ClientModel } = Object.getOwnPropertyNames(a.clients)
.reduce((map: any, key: string) => {
map[key] = new ClientModel(key, a.clients[key].Forename, a.clients[key].Surname);
return map;
}, {});
经过 basarat 的评论并仔细查看 Object.keys()
,Object.keys
比 Object.getOwnPropertyNames()
更适合在这里使用。不同的是后者 returns 属性也是不可枚举的。它在这种特殊情况下没有实际区别,但应该使代码的意图更加明确。其他一切都保持不变。