javascript tutorial - [Solved-3 Solutions] How do we remove a key from a javascript object ? - javascript - java script - javascript array



Problem:

How do we remove a property from a JavaScript object ?

var thisIsObject= {
   'Cow' : 'Moo',
   'Cat' : 'Meow',
   'Dog' : 'Bark'
};
click below button to copy the code. By JavaScript tutorial team

WE wanted to do a function that removes by key:

removeFromObjectByKey('Cow');
click below button to copy the code. By JavaScript tutorial team

Solution 1:

The delete operator allows we 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;
click below button to copy the code. By JavaScript tutorial team

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

Solution 2:

If we 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
click below button to copy the code. By JavaScript tutorial team

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

thisIsObject = _.omit(thisIsObject,'Cow');
click below button to copy the code. By JavaScript tutorial team

With pure JavaScript, use:

delete thisIsObject['Cow'];
click below button to copy the code. By JavaScript tutorial team

Another option with pure JavaScript.

thisIsObject.cow = undefined;

thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));
click below button to copy the code. By JavaScript tutorial team

Solution 3:

If we are using a JavaScript shell, it's as easy as:

delete object.keyname;
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - How do we remove a key from a javascript object ?