本文翻译自:How do I remove a key from a JavaScript object? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
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');
#1楼
参考:https://stackoom.com/question/EUuL/如何从JavaScript对象中删除键-重复
#2楼
It's as easy as: 就像这样简单:
delete object.keyname;
or 要么
delete object["keyname"];
#3楼
If you are using Underscore.js or Lodash, there is a function 'omit' that will do it. 如果您使用的是Underscore.js或Lodash,则可以使用函数“忽略”来实现。
http://underscorejs.org/#omit 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: 对于纯JavaScript,请使用:
delete thisIsObject['Cow'];
Another option with pure JavaScript. 纯JavaScript的另一种选择 。
thisIsObject.cow = undefined;
thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));
#4楼
The delete
operator allows you to remove a property from an object. delete
运算符允许您从对象中删除属性。
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, read Understanding Delete for an in-depth explanation. 如果您有兴趣,请阅读《 了解删除》以获取详细说明。