jack_the_beast
jack_the_beast

Reputation: 1971

typescript/angular: can't iterate over Map parsed from json

I'm new to both typescript and angular (coming from quite solid Java/kotlin background). Wrote a class:

export interface GeoData {
    allregions: Map<string, string>;
}

to parse this json:

{"allregions":{"whatever":"WHT","a region":"ARE","something":"SMT"}

The json is correctly read from a file using HttpClient.get() and I can see the correct content in the variable using debug. also, this code:

console.log(data.allregions["whatever"])

correctly prints WHT.

unfortunately, this:

data.allregions.forEach((value: string, key: string) => {
        console.log(key, value);
    });

throws data.allregions.forEach is not a function

also this:

console.log(data.allregions.size)

prints undefined

and this:

console.log(data.allregions.entries.lenght)

throws data.allregions.entries is undefined

what is going on here?

Upvotes: 0

Views: 339

Answers (1)

joy08
joy08

Reputation: 9652

I see you are applying forEach on a object. Combine Object.keys() and forEach()

var data = {"allregions":{"whatever":"WHT","a region":"ARE","something":"SMT"}}
Object.keys(data.allregions).forEach(function(key) {
  console.log(`key: ${key}, value:${data.allregions[key]}`);
});

Upvotes: 1

Related Questions