Loop over object's key/value using TypeScript / Angular2 [duplicate]

送分小仙女□ 提交于 2019-12-05 12:09:53

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 ClientModel objects:

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:

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.keys is 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!