考虑到一个对象:

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

其他回答

使用对象破坏,一个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);

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

const object = { prop1: 10, prop2: 20, prop3: 30, “test prop”: “This is test props” } console.log(object); // 将打印所有 4 props 删除 object.prop1; 删除 object[“test prop”]; console.log(object); // 将打印仅 prop2 和 prop3

下面是ES6如何轻松地删除输入:

让 myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*” }; const removeItem = “regex”; const { [removeItem]: remove,...rest } = myObject; console.log(remove); // “^http://.*” console.log(rest); // Object { ircEvent: “PRIVMSG”, 方法: “newURI” }

这个帖子很古老,我觉得它非常有用,所以我决定分享我写的 unset 函数,如果其他人看到这个帖子,想想为什么它不那么简单,因为它在 PHP unset 函数。

写下这个新的 unset 函数的原因,是保持所有其他变量的指数在这个 hash_map. 查看下面的例子,看看如何在从 hash_map 中删除值后没有改变“test2”的指数。

function unset(unsetKey, unsetArr, resort) { var tempArr = unsetArr; var unsetArr = {}; delete tempArr[unsetKey]; if (resort) { j = -1; } for (i in tempArr) { if (typeof(tempArr[i]) !== 'undefined') { if (resort) { j++; } else { j = i; } unsetArr[j] = tempArr[i]; } } return unsetArr; } var unsetArr = ['test', 'deletedString', 'test2']; console.log(unset('1', unsetArr, true)); // output Object {0: "test", 1: "test2"} console.log(unset('1', unsetArr, false)); // output Object {0: "test", 2: "test2"}