3

Is there any way to update the value of a created key value pair map in angular 4+.

say i have:

testMap: Map<number, string> = new Map<number, string>();

ngOnInit() {
    this.testMap.set(1, "A");
    this.testMap.set(2, "B");
    this.testMap.set(3, "C");
    this.testMap.set(4, "D");
    this.testMap.set(5, "E");
}

changeValue(id){
    //id is the one of the keys of the map whose value needs to be altered
    //let say (id=3)
    this.testMap.put(id,"ChangedValue"); //PUT is from java
}
Vithushan
  • 503
  • 3
  • 9
  • 34

1 Answers1

11

You can just you set:

this.testMap.set(id, "ChangedValue")
lupus137
  • 383
  • 3
  • 10
  • 1
    Thanks. This works. What if the map contains an object as value. Say {id:number, name:string}. Will i be able to change the name only of the object for matched key while having the same id inside the object. Or should i update as whole object – Vithushan Oct 29 '18 at 03:27
  • 3
    If you want to update a property of an object in a Map all you need to do is get the object and change the property. `const obj = myMap.get(key); obj.name = "new name";` that's it, the object is by reference so it will automatically be reflected in the entry stored in the Map. – JaredMcAteer May 28 '20 at 19:55
  • You could also do `const obj = myMap.get(key); myMap.set(key, {...obj, name})` – Scott Wager Dec 26 '20 at 11:57