Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  106] [ 7]  / answers: 1 / hits: 5483  / 5 Years ago, sat, april 27, 2019, 12:00:00

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?


More From » javascript

 Answers
1

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));




[#7860] Thursday, April 25, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 3 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
;