一尘不染

从对象中删除属性 (JavaScript)

JavaScript

假设我创建一个对象如下:

let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*",
};

我应该如何删除属性regex以结束新myObject的如下?

let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
};

阅读 196

收藏
2022-01-02

共1个答案

一尘不染

要从对象中删除属性(改变对象),您可以这样做:

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);

如果你想要一个对象,除了一些之外,所有的键都是原始的,你可以使用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
2022-01-02