1823

Let's say we have an object with this format:

var thisIsObject= {
   'Cow' : 'Moo',
   'Cat' : 'Meow',
   'Dog' : 'Bark'
};

I wanted to do a function that removes by key:

removeFromObjectByKey('Cow');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Martin Ongtangco
  • 22,657
  • 16
  • 58
  • 84
  • 4
    Do you want the function to be a jQuery function or what does this have to do with jQuery? – dst Aug 11 '10 at 05:01
  • 27
    That is actually a JavaScript object, associative arrays do not exist in JavaScript. – alex Aug 11 '10 at 05:05
  • 3
    Yeah just some confusion with terminology I think, ie it's Javascript not Jquery, and it's an object not array (OP may come from other languages with associative arrays). – thomasrutter Aug 11 '10 at 05:12

3 Answers3

3086

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

let animals = {
  'Cow': 'Moo',
  'Cat': 'Meow',
  'Dog': 'Bark'
};

delete animals.Cow;
delete animals['Dog'];

console.log(animals);

If you're interested, read Understanding Delete for an in-depth explanation.

uingtea
  • 6,002
  • 2
  • 26
  • 40
jessegavin
  • 74,067
  • 28
  • 136
  • 164
  • 58
    If you are looping over keys in an object, and delete them if they match a certain value, does this affect the key index while you are looping over it? – CMaury Feb 04 '13 at 15:57
  • 11
    Beware that IE8 may throw an exception when using `delete` in certain circumstances. See http://stackoverflow.com/questions/1073414/deleting-a-window-property-in-ie – nullability Apr 09 '13 at 20:58
  • 4
    Does anyone know the runtime of this operation? – Ozymandias May 31 '16 at 18:31
  • 1
    This doesn't actuallyremove a ey from a map. – quantumpotato Jun 16 '18 at 13:32
  • 4
    In 10 years of JS-focused development in positions big and small, I have never once needed this before now or knew it existed. Thank you, kind sir, for this post. – Randy Hall Nov 07 '18 at 04:14
  • 4
    If your linter is complaining about using the delete keyword, use: `Reflect.deleteProperty(object1, 'property1');` – Ben174 Feb 14 '19 at 23:01
  • 2
    If you need to perform this operation in a very optimized way, for example when you’re operating on a large number of objects in loops, another option is to set the property to `undefined`. Due to its nature, the performance of `delete` is a lot slower than a simple reassignment to `undefined`, more than 50x times slower See https://jsperf.com/delete-vs-undefined-vs-null/16 Using `delete` is still very fast, you should only look into this kind of performance issues if you have a very good reason to do so, otherwise it’s always preferred to have a more clear semantic and functionality. – Junius Aug 14 '19 at 00:51
  • @JoshBedo I've done testing (at least in Chrome console as of 2021), and delete from an object does not leave an undefined (it wouldn't make sense to have a key+value object that has "undefined" in it anyway). If I were to delete an entry from an _array_ (not an object), I *would* get an undefined entry in the array. – ryanm Oct 20 '21 at 19:39
  • 1
    testing on Chrome, Firefox, and a few others also verified it doesn't leave an undefined value for the deleted key...just removes the key and anything connected to it inside the object. And benchmarking delete is only between 8-10% slower than setting the key to undefined. I agree with ryanm's comment; (using OP's data) calling thisIsObject.Cow after you delete it returns undefined anyway. Does anyone have logic why setting 'Cow' to undefined and keeping it in the object (and memory) would be favorable? Maybe for older browsers? – Viking NM Feb 07 '22 at 14:40
  • 1
    hi @jessegavin i have array '{62 => 105, 59 => 3.33}' i wnat to delete 59 and its value how i can do that – Hamza Qureshi Jan 29 '23 at 17:55
  • hello @HamzaQureshi. you can also delete numerical keys. however, just consider js would convert them to strings and 62 may clash with '62'. i had to change your syntax, as it's not javascript: var arr = {62 : 105, 59 : 3.33}; console.log(arr); delete arr[62]; console.log(arr); – alex May 01 '23 at 07:14
283

If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit

var thisIsObject= {
    'Cow' : 'Moo',
    'Cat' : 'Meow',
    'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object

=> {'Cat' : 'Meow', 'Dog' : 'Bark'}  //result

If you want to modify the current object, assign the returning object to the current object.

thisIsObject = _.omit(thisIsObject,'Cow');

With pure JavaScript, use:

delete thisIsObject['Cow'];

Another option with pure JavaScript.

thisIsObject = Object.keys(thisIsObject).filter(key =>
    key !== 'cow').reduce((obj, key) =>
    {
        obj[key] = thisIsObject[key];
        return obj;
    }, {}
);
trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
Mohammed Safeer
  • 20,751
  • 8
  • 75
  • 78
  • 41
    Downvoted. The thing is that both in underscore and lodash _.omit returns new object, does not modify the current one. So, this is slightly a different thing. – shabunc Jul 01 '15 at 01:36
  • 10
    @shabunc The same with pure javascript. `delete o.properrty` does a lot more harm than good behind the scenes, as it changes `o`‘s hidden class and makes it a generic slow object. – Mateusz Nowak Dec 20 '15 at 10:09
  • 1
    @MateuszNowak no it is not the same. You are talking about implementation details which can vary, but in javascript per se `delete` modifies object, does not creat a new one. – shabunc Dec 20 '15 at 10:15
  • 6
    object.property = undefined is legit. Worked perfectly! (upvoted) – tonejac Sep 27 '16 at 15:56
  • 1
    Good To Remember: if the keys of your object are numbers, then you may need to, `_.omit(myJSONobject, key.toString())` – Rahul Reddy Nov 05 '16 at 17:23
  • 79
    Upvoted. A new immutable object is preferable in many cases. – Dominic Aug 13 '17 at 19:50
  • 1
    FYI [omit has been deprecated from lodash and replaced by pickBy](https://github.com/lodash/lodash/issues/2930) – Karl Pokus Jan 25 '18 at 11:29
  • @KarlPokus Thanks for the Information. Anyway Lodash 5.0.0, yet to release. No deprecated warning till now (4.17.4). Thanks – Mohammed Safeer Jan 26 '18 at 07:24
  • 1
    Upvoted: Use this for **react-js** – bhathiya-perera Aug 20 '18 at 16:49
  • 5
    I am sorry for the downvote, but thisIsObject.cow = undefined; is very misleading. Object.keys(thisIsObject) will still pick up 'cow'. So it's not really deleted. – Patrik Beck Dec 20 '18 at 09:13
  • 2
    Assigning to `undefined` is not the same as `delete` – theUtherSide May 15 '19 at 13:51
  • `thisIsObject.cow = undefined` does work when I parse the object back. – khan May 17 '20 at 07:14
  • The last example is used if there are more cow keys in the object? – Timo May 25 '22 at 08:55
172

It's as easy as:

delete object.keyname;

or

delete object["keyname"];
kalehmann
  • 4,821
  • 6
  • 26
  • 36
ANIL MIRGE
  • 1,763
  • 1
  • 10
  • 2
  • 6
    If the key is generated number, and we does not know about it existing we can do next: `const unknownKey = 100500;` `delete object[\`${unknownKey}\`];` – Sergii Jul 10 '20 at 15:40
  • 9
    How this answer is different from first one? – Afzal Ali Jun 25 '21 at 06:05