Javascript 使用 TypeScript/Angular2 循环对象的键/值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37667436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop over object's key/value using TypeScript / Angular2
提问by Sommereder
How can I iterate over a Object using TypeScript and being able to access key and value?
如何使用 TypeScript 迭代对象并能够访问键和值?
My json object looks something like this:
我的 json 对象看起来像这样:
{
"clients": {
"123abc": {
"Forename": "Simon",
"Surname": "Sample"
},
"456def": {
"Forename": "Charlie",
"Surname": "Brown"
}
}
}
The clients object to be filled is made of client models looking like:
要填充的客户端对象由客户端模型组成,如下所示:
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;
}
}
回答by Nikos Paraskevopoulos
Given:
鉴于:
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
) {}
}
Here is how to get an array of ClientModelobjects:
以下是获取ClientModel对象数组的方法:
var clientList: ClientModel[] = Object.getOwnPropertyNames(a.clients)
.map((key: string) => new ClientModel(key, a.clients[key].Forename, a.clients[key].Surname));
...and here how to get a map from string(id) to ClientModel:
...这里是如何从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;
}, {});
After the comment from basarat and taking a closer look at Object.keys(), Object.keysis more appropriate for use here than Object.getOwnPropertyNames(). The difference is that the latter returns non-enumerable properties too. It has no practical difference in this particular case, but should make the intent of the code more explicit. Everything else remains the same.
经过 basarat 的评论并仔细查看后Object.keys(),Object.keys比Object.getOwnPropertyNames(). 不同之处在于后者也返回不可枚举的属性。在这种特殊情况下它没有实际区别,但应该使代码的意图更加明确。其他一切都保持不变。

