463

How can I remove an item from a JavaScript object?

Like this:

var test = {'red':'#FF0000', 'blue':'#0000FF'};
test.remove('blue');
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
ezebemmel
  • 4,751
  • 2
  • 16
  • 7

1 Answers1

797

var test = {'red':'#FF0000', 'blue':'#0000FF'};
delete test.blue; // or use => delete test['blue'];
console.log(test);

this deletes test.blue

Jonathan
  • 2,700
  • 4
  • 23
  • 41
matchew
  • 19,195
  • 5
  • 44
  • 48
  • 2
    This works great, you can check it here live: http://jsfiddle.net/b8whD/2/ – Mohammed Swillam Jun 09 '11 at 15:21
  • 2
    What if we've an object like that : `{0: 'red', 1:'green', 2:'blue'}` `delete test.0` will fail. – Hotgeart Sep 15 '15 at 16:41
  • 10
    @Hotgeart but `delete test[0]` will succeed. Although, if you are using naturally incrementing integers for your object keys maybe consider an array? – matchew Sep 15 '15 at 16:45
  • 1
    Does `delete` added in ES6? – Mohammad Kermani Aug 17 '16 at 12:28
  • 7
    @Kermani No, `delete` has existed since ES1. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Specifications – Patrick Finnigan Sep 17 '16 at 16:42
  • 7
    @PatrickFinnigan It is funny, because I did not expect to see any easy good from ES1 :) – Mohammad Kermani Sep 17 '16 at 17:03
  • 1
    How is it performance wise? Has anyone done testing around it? – Saurabh Gupta Nov 01 '17 at 20:34
  • 1
    delete does not works at node 8.11.*, what is the solution? – 151291 Aug 23 '18 at 09:04
  • 1
    @151291 I can confirm that the above works for node 8.11.3 and 10.9.0. I am unsure of your problem. However, If you wish for a more *modern* solution you could try `Object.keys(test).reduce((a,b) => b === 'blue' ? ({...a}) : ({...a, [b]: test[b]}),{})` But note that this will note mutate test, but rather create a new Object whose only entry would be `{red: '#FF0000'}` – matchew Aug 23 '18 at 13:59
  • 1
    delete isn't working for me in mongoose, however, I can just set an object to an empty object (if I wanted to delete/hide the whole thing) and it does the trick. – Bradyo Apr 03 '20 at 05:09
  • 1
    Destructuring an object would be a prominent solution considering ES6 @MohammadKermani – perfectionist1 Feb 24 '21 at 14:02