2

I would need some help, because I am stuck. I have problems defining a simple method in angular4 (TypeScript) that gets an argument of the type Map. All I want is to iterate over the elements in the Map. Nothing special.

When I try to iterate over the Map object map2 I get the following error.

Error: ERROR TypeError: map2.forEach is not a function

doStuff(map2: Map<string, string>):number{
  //I get an ERROR here, because map2 is not recognised as a Map()?
  map2.forEach((value: string, key: string) => {
  console.log(key, value);  
  });

  let map = new Map();
  map.set("A","B");
  map.set("C","d");

  console.log(map.get("A")+" :"+ map.size);
  //THIS WORKS
  map.forEach((value: string, key: string) => {
  console.log(key, value);
   });
    }
});

This is how I call the method from another method

...
//some other method
let map4 = JSON.parse('{ "myString": "string", "myNumber": "4" }');
this.myNumber = this.doStuff(map4);
...
2
  • How are you calling the function? What are you passing to it? Commented Jun 10, 2018 at 20:29
  • 1
    Your call to JSON.parse returns an anonymous object; it does not return a Map. Commented Jun 10, 2018 at 21:14

1 Answer 1

2

You need to convert a literal object (that is returned by JSON.parse) into a Map to pass it to doStuff. You can use Object.entries (available from ES2017) for that:

let map4 = JSON.parse('{ "myString": "string", "myNumber": "4" }');
this.myNumber = this.doStuff(new Map(Object.entries(map4)));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.