Languages

TypeScript - iterate over dictionary

3 points
Asked by:
Kate_C
2860

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 answers
2 points
Answered by:
Kate_C
2860

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.