考虑到一个对象:

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

其他回答

另一个替代方案是使用 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()。

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

您可以使用如下的过滤器。

var myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*” }; // Way 1 let filter1 = {} Object.keys({...myObject}).filter(d => { if(d!=='regex'){ filter1[d] = myObject[d]; }) console.log(filter1) // Way 2 let filter2 = Object.fromEntries(Object.entries({...myObject}).filter(d => d[0]!=='regex' )) console.log(filter2)

我用Lodash的“Unset”来让它发生在一个被遗弃的对象中......这只需要写小逻辑来找到由遗弃方法所期望的财产密钥的路径。

返回财产路径作为序列的方法

var a = {"bool":{"must":[{"range":{"price_index.final_price":{"gt":"450", "lt":"500"}}}, {"bool":{"should":[{"term":{"color_value.keyword":"Black"}}]}}]}}; function getPathOfKey(object,key,currentPath, t){ var currentPath = currentPath || []; for(var i in object){ if(i == key){ t = currentPath; } else if(typeof object[i] == "object"){ currentPath.push(i) return getPathOfKey(object[i], key,currentPath) } } t.push(key); return t; } document.getElementById("output").innerHTML =JSON.stringify(getPathOfKey(a,"price_index.final_price")) <div id="output"> </div>

然后只使用Lodash unset方法从对象中移除财产。

var unset = require('lodash.unset'); unset(a, getPathOfKey(a,“price_index.final_price”));

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

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