1

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
});
6
  • 3
    I guess you need to keep a reference. const myKey = { id: 1 };. Now use myKey as first param to set and delete. Commented Aug 5, 2019 at 20:37
  • i did that, but it returns false Commented Aug 5, 2019 at 20:39
  • 1
    why not take the id as key? do you have a special reason, why it should be an object? Commented Aug 5, 2019 at 20:41
  • 2
    What do you mean, "returns false"? And it works fine for me: jsfiddle.net/khrismuc/vwd0tjqo Commented Aug 5, 2019 at 20:41
  • @NinaScholz yes I know that I can do so, i just want to understand the concept Commented Aug 5, 2019 at 20:45

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

i tried this way many times before posting this question and it returned false in chrome console .. that's why i came here.. but it works now, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.