Can't iterate through a map in Angular 4
I am building a frontend using Angular 4 and I came across a strange error. Whenever I execute the code below:
private createProductTree(productData: Map<number, any>): Map<number, Node> {
const productTree = new Map<number, Node>();
// Iterate over menu-item objects.
for (let key of productData.keys()) {
const product = productData.get(key);
if (product.type === 'menu-item') {
const node = new Node(product);
productTree.set(key, node);
}
}
return productTree;
}
I am getting the following error: Type 'IterableIterator<number>' is not an array type or a string type.
on line for (... of ...)
.
I'm not sure what I am doing wrong. The code for
is the same as the one I saw here .
source to share
You are not doing the correct iteration Map
. Map
implements an interface iterable
and returns an array, where the first element is the key and the second is the value. Below is an example from the documentation :
var myMap = new Map();
myMap.set('0', 'foo');
myMap.set(1, 'bar');
myMap.set({}, 'baz');
for (var v of myMap) {
console.log(v);
}
Logs:
["0", "foo"]
[1, "bar"]
[Object, "baz"]
So for your example, it would be:
for (let entry of productData) {
const product = entry[1];
if (product.type === 'menu-item') {
const node = new Node(product);
productTree.set(entry[0], entry[1]);
}
}
However, this requires target=es6
c tsconfig
.
If your goal es5
is you can use it like this:
for (let entry of Array.from(productData.entries())) {
...
}
Or use forEach
instead:
Array.from(productData.entries()).forEach((entry)=> {
const product = entry[1];
if (product.type === 'menu-item') {
const node = new Node(product);
productTree.set(entry[0], entry[1]);
}
}
source to share