从对象中删除属性 (JavaScript) [英] Remove properties from objects (JavaScript)
问题描述
假设我创建一个对象如下:
Say I create an object as follows:
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*",
};
我应该如何删除属性 regex
以得到新的 myObject
如下?
How should I remove the property regex
to end up with new myObject
as follows?
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
};
推荐答案
要从对象中删除属性(改变对象),您可以这样做:
To remove a property from an object (mutating the object), you can do it like this:
delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];
演示
var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
delete myObject.regex;
console.log(myObject);
对于任何有兴趣阅读更多相关信息的人,Stack Overflow 用户 kangax 写了一篇关于他们博客上的 delete
声明,了解删除.强烈推荐.
For anyone interested in reading more about it, Stack Overflow user kangax has written an incredibly in-depth blog post about the delete
statement on their blog, Understanding delete. It is highly recommended.
如果您想要一个 新 对象,其中包含原始键的所有键,除了一些键,您可以使用 解构.
If you'd like a new object with all the keys of the original except some, you could use the destructuring.
演示
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
const {regex, ...newObj} = myObject;
console.log(newObj); // has no 'regex' key
console.log(myObject); // remains unchanged
这篇关于从对象中删除属性 (JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!