Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  136] [ 4]  / answers: 1 / hits: 25092  / 8 Years ago, mon, june 6, 2016, 12:00:00

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

More From » foreach

 Answers
171

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.


[#61882] Friday, June 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braydon

Total Points: 0
Total Questions: 102
Total Answers: 111

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
braydon questions
Tue, Nov 23, 21, 00:00, 3 Years ago
Mon, Dec 21, 20, 00:00, 4 Years ago
Fri, May 15, 20, 00:00, 4 Years ago
Fri, Mar 27, 20, 00:00, 4 Years ago
;