Loop over object's key/value using TypeScript / Angular2

24,773

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.

Share:
24,773
Sommereder
Author by

Sommereder

Designer. Developer. Digitalist.

Updated on June 08, 2020

Comments

  • Sommereder
    Sommereder almost 4 years

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

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