I’m fairly new and trying to understand maps in javascript.
I have below code.
const topmap = new Map();
const map1 = new Map();
const map2 = new Map();
const set1 = new Set();
map1.set('x','y');
map1.set('a','b');
set1.add(map1);
set1.add(map2);
topmap.set('ID',set1);
console.log(topmap.get('ID').size);
topmap.get('ID').forEach(x => {
if(x.has('x')){x.delete('x')} )
}
)
console.log(topmap.get('ID').size)
Anyone has any idea why both lines getting their size returning 2 even tho i deleted one map in line 18
2
Answers
Because your
topmap.get('ID').size
represents yourset1
has two map.You just delete map’s element rather than map.
On your code above at line if(x.has(‘x’)){x.delete(‘x’)} ), you redundant ) in end of line.
If you want to remove the entire Map (map1) from the Set (set1), you can use the set1.delete(map1) method. Here’s the corrected code: