how to delete an object with an object key from a map object?
for example if i created a map object called members
const members = new Map();
here's the normal way for adding a new object inside members
//members.set(key, value);
members.set('Evelyn',{name: 'Evelyn', age: 25});
//here's how can we delete this object
members.delete('Evelyn');
but when i started reading about map objects in es6 i was confused that the keys can be an object too!!
Map is an object that lets you store key-value pairs where both the keys and the values can be objects
if so how can i delete the one with the object key ?
//key as an object
members.set({id: 1}, {
name: 'Evelyn',
age: 30
});
You need eiter the same object reference of the key or seach with some infomation of the object.
var members = new Map, id = 1, key; members.set({ id: 1 }, { name: 'Evelyn', age: 30 }); console.log([...members]); // one element for (key of members.keys()) if (key.id === id) members.delete(key); console.log([...members]); // []
.as-console-wrapper { max-height: 100% !important; top: 0; }
let objectKey = {id: 1};
members.set(objectKey, {
name: 'Evelyn',
age: 30
});
members.delete(objectKey);
As of my knowledge Maps compare via reference so this would be the only way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.