0

I am sure that this should be quite simple to resolve but I couldn´t figure it out. I have a Map object that contains a set of strings as keys with initial values set to zero.

let n = new Map();
n.set("example1", 0);
n.set("example2", 0);
n.set("example3", 0);

const conditions = () =>{
   let exampStr;
   //random set of conditions
   return exampStr; // can return example1, example2 o example3 
}

// use the result of the function conditions() to add 1 to the value of the map n at the given key. 

I have a function that should ++ the value of a certain key given that a set of conditions are fulfilled. I have no idea how to alter the value of a given key of this map by passing the correspondent key.

  • 2
    Get the value with `n.get()`, add 1, and save it with `n.set()`? Is that what you're asking? – Pointy Apr 10 '20 at 17:52

1 Answers1

1

You can't update the value of a given key in a Map directly. What you can do is to simply get the value first, increment it by 1, and re-assign it to the same key:

const key = conditions();
n.set(key, n.get(key) + 1);
Terry
  • 63,248
  • 15
  • 96
  • 118