考虑到一个对象:

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

如何删除财产 regex 以完成下一个 myObject?

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

当前回答

分布式合成(ES6)

要完成 Koen 的答案,如果您想使用扩散合成来删除动态变量,您可以这样做:

const key = 'a'; const { [key]: foo,...rest } = { a: 1, b: 2, c: 3 }; console.log(foo); // 1 console.log(rest); // { b: 2, c: 3 }

* foo 将是一个新的变量,值为 a(即 1)。

延伸答案

每个人都有自己的优点和缺点(查看此性能比较):

删除操作员

它是可读的和短暂的,但是,它可能不是最好的选择,如果你在大量的对象上运行,因为它的性能不优化。

delete obj[key];

重新分配

它比删除更快两倍,但财产不会被删除,并且可以被异化。

obj[key] = null;
obj[key] = false;
obj[key] = undefined;

扩展运营商

{ [key]: val, ...rest } = obj;

其他回答

var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; 删除 myObject.regex; console.log ( myObject.regex); // logs: undefined

它在Firefox和Internet Explorer工作,我认为它在其他所有工作。

您可以使用 Delete Property 删除对象中的财产[键]

使用 ramda#dissoc 您将获得一个新的对象,而无需属性 regex:

const newObject = R.dissoc('regex', myObject);
// newObject !== myObject

你也可以使用其他功能来实现相同的效果 - 忽略,选择,...

ECMAScript 2015(或ES6)配备了内置的反射对象,可以通过使用目标对象和属性密钥的 Reflect.deleteProperty() 函数来删除对象属性:

Reflect.deleteProperty(myJSONObject, 'regex');

相当于:

delete myJSONObject['regex'];

但是,如果对象的属性无法配置,则不能通过删除属性函数或删除操作员删除它:

let obj = Object.freeze({ prop: "value" });
let success = Reflect.deleteProperty(obj, "prop");
console.log(success); // false
console.log(obj.prop); // value

Object.freeze() 使对象的所有属性不可配置(除其他事物外)。 deleteProperty 函数(以及 delete 运营商)在试图删除其任何属性时返回虚假。

删除和删除的区别在于使用严格模式时:

"use strict";

let obj = Object.freeze({ prop: "value" });
Reflect.deleteProperty(obj, "prop"); // false
delete obj["prop"];
// TypeError: property "prop" is non-configurable and can't be deleted

有几种方法可以从物体中删除属性:

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