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');
-
4Do you want the function to be a jQuery function or what does this have to do with jQuery?dst– dst2010年08月11日 05:01:15 +00:00Commented Aug 11, 2010 at 5:01
-
28That is actually a JavaScript object, associative arrays do not exist in JavaScript.alex– alex2010年08月11日 05:05:30 +00:00Commented Aug 11, 2010 at 5:05
-
3Yeah just some confusion with terminology I think, ie it's Javascript not Jquery, and it's an object not array (OP may come from other languages with associative arrays).thomasrutter– thomasrutter2010年08月11日 05:12:05 +00:00Commented Aug 11, 2010 at 5:12
3 Answers 3
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.
12 Comments
delete
in certain circumstances. See stackoverflow.com/questions/1073414/… Reflect.deleteProperty(object1, 'property1');
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;
}, {}
);
13 Comments
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.It's as easy as:
delete object.keyname;
or
delete object["keyname"];
4 Comments
const unknownKey = 100500;
delete object[`${unknownKey}`];