使用TypeScript / Angular2循环对象的键/值 [英] Loop over object's key/value using TypeScript / Angular2

查看:97
本文介绍了使用TypeScript / Angular2循环对象的键/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用TypeScript迭代Object并能够访问键和值?

How can I iterate over a Object using TypeScript and being able to access key and value?

我的json对象如下所示:

My json object looks something like this:

{
    "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;
    }
}


推荐答案

鉴于:

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的数组 objects:

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));

...以及如何从字符串中获取地图(id)to ClientModel

...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;
    }, {});






在巴萨拉特的评论后仔细看看在 Object.keys() Object.keys 对象更适合在这里使用.getOwnPropertyNames()。不同之处在于后者也返回不可枚举的属性。它在这种特殊情况下没有实际区别,但应该使代码的意图更加明确。其他一切都保持不变。


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.

这篇关于使用TypeScript / Angular2循环对象的键/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆