Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot iterate through Map in Angular 4

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.

like image 958
Felipe Avatar asked Mar 27 '26 07:03

Felipe


1 Answers

You 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]);
  }
}
like image 144
Max Koretskyi Avatar answered Mar 28 '26 21:03

Max Koretskyi