I have this code here:

const myMap = new Map()

myMap.set("banana", true)
myMap.set("apple", true)

Object.keys(myMap).forEach(key => {myMap.set(key, false)})

console.log(myMap.get("banana")) // returns true should return false
console.log(myMap.get("apple")) // returns true should return false

I want to set all the values of this Map to false, but it doesn't work at all.

I've tried something like this:

Object.keys(myMap).forEach(key => myMap[key] = false)

but this doesn't work either.

Is there a way to fill all keys of a Map to a specific value?

2 Answers

2
CertainPerformance On Best Solutions

You have to specifically call Map.set in order to set a value in a Map. myMap[key] = value will only work for plain objects. You should also use myMap.keys() to get an iterator of the map's keys:

const myMap = new Map();

myMap.set("banana", true);
myMap.set("apple", true);

[...myMap.keys()].forEach((key) => {
  myMap.set(key, false);
});

console.log(myMap.get("banana"));
console.log(myMap.get("apple"));

2
Shidersz On

A Map has a .forEach() method for traverse it, that you can use in this particular case:

const myMap = new Map();
myMap.set("banana", true);
myMap.set("apple", true);

myMap.forEach((value, key, map) => map.set(key, false));

console.log(
  "Banana:", myMap.get("banana"),
  "Apple:", myMap.get("apple")
);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

The documentation of the callback invoked on each element, from MDN, says:

The forEach method executes the provided callback once for each key of the map which actually exist. It is not invoked for keys which have been deleted. However, it is executed for values which are present but have the value undefined. The callback is invoked with three arguments:

  • the element value
  • the element key
  • the Map object being traversed