考虑到一个对象:

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

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

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

当前回答

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

其他回答

另一个解决方案,使用 Array#reduce。

(六)

const myObject = { ircEvent: 'PRIVMSG',方法: 'newURI', regex: '^http://.*', }; const myNewObject = Object.keys(myObject).reduce((obj, key) => { key!=='regex'? obj[key] = myObject[key] : null; return obj; }, {}); console.log(myNewObject);

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

例如:

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 }

使用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}

短答

var obj = {
  data: 1,
  anotherData: 'sample'    
}
delete obj.data //this removes data from the obj

你被留在

var obj = {
  anotherData: 'sample'    
}

我用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”));