考虑到一个对象:

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

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

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

当前回答

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

其他回答

正确的路

到2023年,你只能在一个线上做到这一点:

delete myObject.regex;

delete myObject["regex"];

(例如,如果你有一个对象obj与一个属性称为关键一,你不能做obj.key一,所以这里是obj(“关键一”)。

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

另一个解决方案,使用 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);

短答

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

你被留在

var obj = {
  anotherData: 'sample'    
}

尝试下面的方法. 将对象属性值分为未定义。

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