How do I remove a key from a JavaScript object?

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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;

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

Solution 2 - Javascript

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

Solution 3 - Javascript

It's as easy as:

delete object.keyname;

or

delete object["keyname"];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin OngtangcoView Question on Stackoverflow
Solution 1 - JavascriptjessegavinView Answer on Stackoverflow
Solution 2 - JavascriptMohammed SafeerView Answer on Stackoverflow
Solution 3 - JavascriptANIL MIRGEView Answer on Stackoverflow