I am creating 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 get the following error: Type 'IterableIterator<number>' is not an array type or a string type.
in the for (... of ...)
line.
I am not sure what I am doing wrong. The for
code is the same as the one I saw here.
I am creating 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 get the following error: Type 'IterableIterator<number>' is not an array type or a string type.
in the for (... of ...)
line.
I am not sure what I am doing wrong. The for
code is the same as the one I saw here.
- According to this discussion, it could be related to the Javascript version that you are targeting. It should work for ES6. – Martin Parenteau Commented Jul 29, 2017 at 19:22
-
@ConnorsFan, even in es6 this is not the correct way to iterate the Map as I mention in my answer. If one uses
keys()
there's no need to usefor..of
.forEach
would be a better option – Max Koretskyi Commented Jul 29, 2017 at 19:23
2 Answers
Reset to default 5You are not iterating Map
correctly. Map
implements iterable
interface and returns an array where first element is the key and the second element is the value. Here is an example from the docs:
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
in tsconfig
.
If your target is es5
, 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]);
}
}
for (const key in productData) { }
of is basically forEach and iterates over values, in accesses the keys of an object.