Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
}
like image 905
Sommereder Avatar asked Jan 06 '23 22:01

Sommereder


1 Answers

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.

like image 178
Nikos Paraskevopoulos Avatar answered Jan 08 '23 12:01

Nikos Paraskevopoulos