考虑到一个对象:

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

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

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

当前回答

我们可以使用

使用删除 object.property 使用删除 object[‘property’] 使用休息,删除多个属性

让 myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”, “regex1”: “^http://.*”, “regex2”: “^http://.*”, “regex3”: “^http://.*”, “regex4”: “^http://.*” }; 删除 myObject.regex; // 使用删除 object.property // 或删除 myObject(‘regex1’); // 使用删除 object(‘property’) const { regex2, regex3, regex4,...newMyObject } = myObject; console.log(n)

其他回答

一个没有财产的物体的克隆:

例如:

let object = { a: 1, b: 2, c: 3 };

我们必须删除A。

有一个明确的 prop 密钥: const { a,...rest } = 对象; 对象 = 休息; 有一个变量的 prop 密钥: const propKey = 'a'; const { [propKey]: propValue,...rest } = 对象; 对象 = 休息; A cool arrow 函数 <unk>: const removeProperty = (propKey, { [propKey]: propValue,...rest }) => 休息; 对象 = removeProperty('a', 对象); 多种属性 const removeProperties = (object,...keys)

使用

object = removeProperties(object, 'a', 'b') // result => { c: 3 }

const propsToRemove = ['a', 'b']
object = removeProperties(object, ...propsToRemove) // result => { c: 3 }

另一个替代方案是使用 Underscore.js 图书馆。

請注意, _.pick() 和 _.omit() 兩者都返回對象的副本,並且不直接修改原始對象。

参考: 链接 _.pick(对象, *keys)

返回对象的副本,过滤到只有值为白化密钥(或一系列有效的密钥)。

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

_.pick(myJSONObject, "ircEvent", "method");
=> {"ircEvent": "PRIVMSG", "method": "newURI"};

参考: 链接 _.omit(对象, * 关键)

返回对象的副本,过滤以忽略黑名单的钥匙(或一系列的钥匙)。

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

_.omit(myJSONObject, "regex");
=> {"ircEvent": "PRIVMSG", "method": "newURI"};

对于序列,可以类似的方式使用 _.filter() 和 _.reject()。

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

使用Lodash

import omit from 'lodash/omit';

const prevObject = {test: false, test2: true};
// Removes test2 key from previous object
const nextObject = omit(prevObject, 'test2');

使用RAMDA

R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}