考虑到一个对象:
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
如何删除财产 regex 以完成下一个 myObject?
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
考虑到一个对象:
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
如何删除财产 regex 以完成下一个 myObject?
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
当前回答
有几种方法可以从物体中删除属性:
1) 使用点属性附件移除(可变)
2. 使用方形布拉克特属性配件移除(可转换)
const myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”, }; delete myObject[‘regex’]; console.log(myObject); // or const name = ‘ircEvent’; delete myObject[name]; console.log(myObject);
3) 替代选项,但没有改变原始对象,使用对象破坏和休息合成(不变)
const myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”, }; const { regex,...myObjectRest} = myObject; console.log(myObjectRest);
其他回答
要从对象中删除一个属性(指向对象),你可以这样做:
delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];
Demo var myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*” }; 删除 myObject.regex; console.log(myObject);
对于任何有兴趣阅读更多关于它的人来说,Stack Overflow 用户 Kangax 写了一篇关于他们博客的删除声明的令人难以置信的深入博客帖子,理解删除。
如果你想要一个新的对象,除了一些,所有原始的钥匙,你可以使用破坏。
正确的路
到2023年,你只能在一个线上做到这一点:
delete myObject.regex;
或
delete myObject["regex"];
(例如,如果你有一个对象obj与一个属性称为关键一,你不能做obj.key一,所以这里是obj(“关键一”)。
使用 ramda#dissoc 您将获得一个新的对象,而无需属性 regex:
const newObject = R.dissoc('regex', myObject);
// newObject !== myObject
你也可以使用其他功能来实现相同的效果 - 忽略,选择,...
使用对象破坏,一个ECMAScript 6功能,它是如此简单:
const { a, ...rest } = { a: 1, b: 2, c: 3 };
或与问题样本:
const myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
const { regex, ...newObject } = myObject;
console.log(newObject);
你可以在Babel try-out编辑中看到它。
编辑:
要重新分配到相同的变量,请使用:
let myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
({ regex, ...myObject } = myObject);
console.log(myObject);
var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; 删除 myObject.regex; console.log ( myObject.regex); // logs: undefined
它在Firefox和Internet Explorer工作,我认为它在其他所有工作。