Coder Perfect

How do I remove a key from a JavaScript object? [duplicate]


Assume we have an object of the following format:

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

I wanted to create a function that eliminates items based on their key:


Asked by Martin Ongtangco

Solution #1

You can delete a property from an object with the delete operator.

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 in learning more, read Understanding Delete.

Answered by jessegavin

Solution #2

If you’re using Underscore.js or Lodash, you can use the ‘omit’ function to accomplish this.

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

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

Assign the returning object to the current object if you wish to make changes to it.

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

Use the following code in pure JavaScript:

delete thisIsObject['Cow'];

Another pure JavaScript option.

thisIsObject = Object.keys(thisIsObject).filter(key =>
    key !== 'cow').reduce((obj, key) =>
        obj[key] = thisIsObject[key];
        return obj;
    }, {}

Answered by Mohammed Safeer

Solution #3

It’s as simple as this:

delete object.keyname;


delete object["keyname"];

Answered by ANIL MIRGE

Post is based on