0

How do I delete items from a Map based on a condition, for example:

m = {a:{name: "A"}, b:{name: "B"}, B:{name: "B"}, aa:{name: "A"}}

I wish to remove the two entries where name==="B".

Can I delete in a foreach?

jrbedard
  • 3,662
  • 5
  • 30
  • 34
Baz
  • 12,713
  • 38
  • 145
  • 268
  • Is this an actual [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete)? Or is it an object like in your code? – 4castle Oct 15 '16 at 20:35
  • http://stackoverflow.com/questions/346021/how-do-i-remove-objects-from-a-javascript-associative-array – th7nder Oct 15 '16 at 20:36
  • https://jsfiddle.net/hhoohdnd/ – blex Oct 15 '16 at 20:37

1 Answers1

2

You could iterate the keys and delete accordingly

var m = { a: { name: "A" }, b: { name: "B" }, B: { name: "B" }, aa: { name: "A" } };

Object.keys(m).forEach(function (k) {
    if (m[k].name === 'B') {
        delete m[k];
    }
});

console.log(m);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392