I\'m trying to iterate over a typescript map but I keep getting errors and I could not find any solution yet for such a trivial problem.
My code is:
Using Array.from, Array.prototype.forEach(), and arrow functions:
Iterate over the keys:
Array.from(myMap.keys()).forEach(key => console.log(key));
Iterate over the values:
Array.from(myMap.values()).forEach(value => console.log(value));
Iterate over the entries:
Array.from(myMap.entries()).forEach(entry => console.log('Key: ' + entry[0] + ' Value: ' + entry[1]));
Just a simple explanation to use it in an HTML document.
If you have a Map of types (key, array) then you initialise the array this way:
public cityShop: Map<string, Shop[]> = new Map();
And to iterate over it, you create an array from key values.
Just use it as an array as in:
keys = Array.from(this.cityShop.keys());
Then, in HTML, you can use:
*ngFor="let key of keys"
Inside this loop, you just get the array value with:
this.cityShop.get(key)
Done!
If you don't really like nested functions, you can also iterate over the keys:
myMap : Map<string, boolean>;
for(let key of myMap) {
if (myMap.hasOwnProperty(key)) {
console.log(JSON.stringify({key: key, value: myMap[key]}));
}
}
Note, you have to filter out the non-key iterations with the hasOwnProperty
, if you don't do this, you get a warning or an error.
On Typescript 3.5 and Angular 8 LTS, it was required to cast the type as follows:
for (let [k, v] of Object.entries(someMap)) {
console.log(k, v)
}
You could use Map.prototype.forEach((value, key, map) => void, thisArg?) : void
instead
Use it like this:
myMap.forEach((value: boolean, key: string) => {
console.log(key, value);
});
You can also apply the array map method to the Map.entries() iterable:
[...myMap.entries()].map(
([key, value]: [string, number]) => console.log(key, value)
);
Also, as noted in other answers, you may have to enable down level iteration in your tsconfig.json (under compiler options):
"downlevelIteration": true,