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');
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.
Answered 2023-09-21 08:10:23
delete
in certain circumstances. See stackoverflow.com/questions/1073414/… - anyone Reflect.deleteProperty(object1, 'property1');
- anyone 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;
}, {}
);
Answered 2023-09-21 08:10:23
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. - anyone It's as easy as:
delete object.keyname;
or
delete object["keyname"];
Answered 2023-09-21 08:10:23
const unknownKey = 100500;
delete object[`${unknownKey}`];
- anyone