如何从 JavaScript 对象中删除键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3455405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I remove a key from a JavaScript object?
提问by Martin Ongtangco
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');
回答by jessegavin
The deleteoperator 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 Deletefor an in-depth explanation.
如果您有兴趣,请阅读了解删除以获得更深入的解释。
回答by Mohammed Safeer
If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit
如果你使用 Underscore.js 或 Lodash,有一个函数 '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 optionwith pure JavaScript.
纯 JavaScript 的另一种选择。
thisIsObject.cow = undefined;
thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));
回答by ANIL MIRGE
It's as easy as:
这很简单:
delete object.keyname;
or
或者
delete object["keyname"];

