0

I have some objects inside js Map object. How do we remove object with particular key and value?

let newMap = new Map()

newMap.set('1', {ep: '1', name: 'First test'})
newMap.set('2', {ep: '2', name: 'Second test'})

So, the above example holds two object inside newMap. How can I remove object with ep value '1', so that the newMap hash returns only one object i.e. {ep: '2', name: 'Second test'}.

1
  • 1
    Instead of setting item based on index, set it based on unique key Commented Sep 12, 2018 at 7:02

3 Answers 3

4

You've stored it under the key '1'. So you call delete with that key:

newMap.delete('1');

If you don't know the key you've stored it under, a Map probably isn't the structure you wanted, but you can find it by looping through entries, which returns an array whose entries are arraysin [key, value] format:

for (const entry of newMap.entries()) { // for-of is ES2015+
    if (entry[1].ep === '1') {
        newMap.delete(entry[0]);
        break;
    }
}

...or with ES5:

newMap.entries().some(function(entry) {
    if (entry[1].ep === '1') {
        newMap.delete(entry[0]);
        return true;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

2

You'll have to iterate over the entries and find the object you want to remove, then delete the appropriate key:

let newMap = new Map();
newMap.set('1', {ep: '1', name: 'First test'});
newMap.set('2', {ep: '2', name: 'Second test'});

const entryToRemove = [...newMap.entries()].find(([, { ep }]) => ep === '1');
newMap.delete(entryToRemove[0]);
console.log(newMap); // look in browser console, not snippet console

(Of course, if you can count on the map's key being the same as the ep, just do newMap.delete(epToDelete))

Comments

0

Your map looks like this:

Map { '1' => { ep: '1', name: 'First test' }, '2' => { ep: '2', name: 'Second test' } }

To remove ep:'1' and have onlye ep:'2' you can try this:

newMap.delete('1');

Comments

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.