Code father
Code father

Reputation: 605

How do we remove particular object from js Map object?

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'}.

Upvotes: 0

Views: 169

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

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

Upvotes: 4

Ashish
Ashish

Reputation: 643

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');

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

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))

Upvotes: 2

Related Questions