Languages

TypeScript - iterate over dictionary

3 points
Asked by:
Kate_C
19800

How can I iterate over dictionary of objects in TypeScript?
I have map of object like this:

let dictionary = {
    'key1' : {
        id : 47,
        name : 'Test 1'
    },
    'key2' : {
        id : 51,      
        name : 'Test 2'
    },
    'key3' : {
        id : 141,
        name : 'Test 3'
    },
};

What is the best and recommended way of doing that?

1 answer
2 points
Answered by:
Kate_C
19800

Quick solution:

for(let key in dictionary) {
    let value = dictionary[key];

    let id = value.id;
    let name = value.name;
}

We can use any other property defined under dictionary value, by using value.propertyName.

We can use standrad for...in loop over object from JavaScript, code example:

// ONLINE-RUNNER:browser;

let dictionary = {
    'key1' : {
        id : 47,
        name : 'Test 1'
    },
    'key2' : {
        id : 51,      
        name : 'Test 2'
    },
    'key3' : {
        id : 141,
        name : 'Test 3'
    },
};

for(let key in dictionary) {
    let value = dictionary[key];

    let id = value.id;
    let name = value.name;

    console.log('key: ' + key + ', id: ' + id  + ', name: ' + name);
}

You can take a look at article, point 3 (3. for...in loop over object example)

 

0 comments Add comment
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join