bcsta
bcsta

Reputation: 2307

Typescript how to call and access dictionary keys from a loop

I have a dictionary like the one below

let dict = {
             a:{
                first:1, 
                second:2
               },
             b:{
                first:2, 
                second:3
               }
           }

I want to loop through the first set of keys and then manipulate the second set of keys. something like the below code:

    for(const firstKey of dict){
        firstKey.first = 5
    }

The problem is that compiler is giving me an error on firstKey.first = 5saying

Property 'first' does not exist on type 'string'. 

Why is this happening? I also tried firstKey[first] which did not work either.

Upvotes: 0

Views: 397

Answers (1)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

The keys are not iterable. You need to use Object.keys() to get an array of keys to iterate, thusly:

for(const key of Object.keys(dict)) { 
   console.log(key, dict[key]);
}

Upvotes: 2

Related Questions