Problem
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:
removeFromObjectByKey('Cow');
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. 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
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;
or
delete object["keyname"];
Answered by ANIL MIRGE
Post is based on https://stackoverflow.com/questions/3455405/how-do-i-remove-a-key-from-a-javascript-object