4

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

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

A lot to learn for old school JavaScript developers. Thank you very much!
Very strongly prefer Object.keys. Same thing (for most purposes stackoverflow.com/a/22658584/390330), simpler and more common in the wild 🌹
@basarat Yes, indeed, Object.keys is more appropriate, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.