Delete in Map not deleting key that are objects

Viewed 1476

I have created a map object

var map_obj = new Map();
map_obj.set({'a':2, 'b':3}, {'c': 4});

now when i tried to use .delete operator

map_obj.delete({'a':2, 'b':3})

It is showing me false and key and value are not deleted. It can be that It is checking for object reference and creating a new object so can't find the equal object. In MDN guide, it is said key can be of any type. So what's happening here and what would be the right way to delete the key ?

This is how delete process is defined in es-6

2 Answers

The easy way, is to store the object reference to a variable.

var map_obj = new Map(),
    object = { a: 2, b: 3 };

map_obj.set(object, {'c': 4});
console.log([...map_obj]);

map_obj.delete(object);
console.log([...map_obj]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you have only parts of the object then you need to find this object by comparing the object.

var map_obj = new Map(),
    a = 2, b = 3,
    key;

map_obj.set({ a: 2, b: 3 }, {'c': 4});
console.log([...map_obj]);

key = Array.from(map_obj.keys()).find(o => o.a === a && o.b === b);

map_obj.delete(key);
console.log([...map_obj]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

The problem here is, that when calling map_obj.delete({'a':2, 'b':3}), you call it with a new Object. Try :

var map_obj = new Map();
x = {'a':2, 'b':3};
map_obj.set(x, {'c': 4});
//...
map_obj.delete(x);

Related