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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With