简体   繁体   English

如何从 JavaScript object 中删除属性?

[英]How do I remove a property from a JavaScript object?

Given an object:给定一个 object:

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

How do I remove the property regex to end up with the following myObject ?如何删除属性regex以结束以下myObject

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

To remove a property from an object (mutating the object), you can do it like this:要从对象中删除属性(改变对象),您可以这样做:

delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];

Demo演示

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

For anyone interested in reading more about it, Stack Overflow user kangax has written an incredibly in-depth blog post about the delete statement on their blog, Understanding delete .对于任何有兴趣阅读更多相关信息的人,Stack Overflow 用户kangax在他们的博客上写了一篇关于delete语句的非常深入的博文, Understanding delete It is highly recommended.强烈推荐。

If you'd like a new object with all the keys of the original except some, you could use the destructuring .如果你想要一个对象,除了一些之外,所有的键都是原始的,你可以使用destructuring

Demo演示

 let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; const {regex, ...newObj} = myObject; console.log(newObj); // has no 'regex' key console.log(myObject); // remains unchanged

Objects in JavaScript can be thought of as maps between keys and values. JavaScript 中的对象可以被认为是键和值之间的映射。 The delete operator is used to remove these keys, more commonly known as object properties, one at a time. delete运算符用于删除这些键,通常称为对象属性,一次删除一个。

 var obj = { myProperty: 1 } console.log(obj.hasOwnProperty('myProperty')) // true delete obj.myProperty console.log(obj.hasOwnProperty('myProperty')) // false

The delete operator does not directly free memory, and it differs from simply assigning the value of null or undefined to a property, in that the property itself is removed from the object. delete操作符不直接释放内存,它不同于简单地将nullundefined的值分配给属性,因为属性本身从对象中删除。 Note that if the value of a deleted property was a reference type (an object), and another part of your program still holds a reference to that object, then that object will, of course, not be garbage collected until all references to it have disappeared.请注意,如果被删除的属性的是一个引用类型(一个对象),并且程序的另一部分仍然持有对该对象的引用,那么该对象当然不会被垃圾收集,直到对它的所有引用都有消失了。

delete will only work on properties whose descriptor marks them as configurable. delete仅适用于描述符将其标记为可配置的属性。

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

This works in Firefox and Internet Explorer, and I think it works in all others.这适用于 Firefox 和 Internet Explorer,我认为它适用于所有其他人。

The delete operator is used to remove properties from objects. delete运算符用于从对象中删除属性。

const obj = { foo: "bar" }
delete obj.foo
obj.hasOwnProperty("foo") // false

Note that, for arrays, this is not the same as removing an element .请注意,对于数组,这与删除元素不同 To remove an element from an array, use Array#splice or Array#pop .要从数组中删除元素,请使用Array#spliceArray#pop For example:例如:

arr // [0, 1, 2, 3, 4]
arr.splice(3,1); // 3
arr // [0, 1, 2, 4]

Details细节

delete in JavaScript has a different function to that of the keyword in C and C++: it does not directly free memory. JavaScript 中的delete与 C 和 C++ 中的关键字的功能不同:它不直接释放内存。 Instead, its sole purpose is to remove properties from objects.相反,它的唯一目的是从对象中删除属性。

For arrays, deleting a property corresponding to an index, creates a sparse array (ie. an array with a "hole" in it).对于数组,删除与索引对应的属性,会创建一个稀疏数组(即其中有一个“洞”的数组)。 Most browsers represent these missing array indices as "empty".大多数浏览器将这些缺失的数组索引表示为“空”。

var array = [0, 1, 2, 3]
delete array[2] // [0, 1, empty, 3]

Note that delete does not relocate array[3] into array[2] .请注意, delete不会将array[3]定位到array[2]

Different built-in functions in JavaScript handle sparse arrays differently. JavaScript 中不同的内置函数处理稀疏数组的方式不同。

  • for...in will skip the empty index completely. for...in将完全跳过空索引。

  • A traditional for loop will return undefined for the value at the index.传统的for循环将为索引处的值返回undefined

  • Any method using Symbol.iterator will return undefined for the value at the index.任何使用Symbol.iterator方法都会为索引处的值返回undefined

  • forEach , map and reduce will simply skip the missing index. forEachmapreduce将简单地跳过丢失的索引。

So, the delete operator should not be used for the common use-case of removing elements from an array.因此, delete运算符不应用于从数组中删除元素的常见用例。 Arrays have a dedicated methods for removing elements and reallocating memory: Array#splice() and Array#pop .数组有专门的方法来删除元素和重新分配内存: Array#splice()Array#pop

Array#splice(start[, deleteCount[, item1[, item2[, ...]]]])数组#splice(start[, deleteCount[, item1[, item2[, ...]]]])

Array#splice mutates the array, and returns any removed indices. Array#splice改变数组,并返回任何删除的索引。 deleteCount elements are removed from index start , and item1, item2... itemN are inserted into the array from index start .从索引start中删除deleteCount元素,并将item1, item2... itemN从索引start插入到数组中。 If deleteCount is omitted then elements from startIndex are removed to the end of the array.如果省略了deleteCount则从 startIndex 开始的元素将被移除到数组的末尾。

let a = [0,1,2,3,4]
a.splice(2,2) // returns the removed elements [2,3]
// ...and `a` is now [0,1,4]

There is also a similarly named, but different, function on Array.prototype : Array#slice .Array.prototype上还有一个名称相似但不同的函数: Array#slice

Array#slice([begin[, end]])数组#slice([begin[, end]])

Array#slice is non-destructive, and returns a new array containing the indicated indices from start to end . Array#slice是非破坏性的,并返回一个新数组,其中包含从startend的指示索引。 If end is left unspecified, it defaults to the end of the array.如果未指定end ,则默认为数组的末尾。 If end is positive, it specifies the zero-based non-inclusive index to stop at.如果end为正数,则指定要停止的从零开始的非包含索引。 If end is negative it, it specifies the index to stop at by counting back from the end of the array (eg. -1 will omit the final index).如果end为负数,则它通过从数组末尾开始倒数来指定要停止的索引(例如,-1 将省略最终索引)。 If end <= start , the result is an empty array.如果end <= start ,结果是一个空数组。

let a = [0,1,2,3,4]
let slices = [
    a.slice(0,2),
    a.slice(2,2),
    a.slice(2,3),
    a.slice(2,5) ]

//   a           [0,1,2,3,4]
//   slices[0]   [0 1]- - -   
//   slices[1]    - - - - -
//   slices[2]    - -[3]- -
//   slices[3]    - -[2 4 5]

Array#pop数组#pop

Array#pop removes the last element from an array, and returns that element. Array#pop从数组中删除最后一个元素,并返回该元素。 This operation changes the length of the array.此操作更改数组的长度。

Old question, modern answer.老问题,现代答案。 Using object destructuring, an ECMAScript 6 feature, it's as simple as:使用对象解构( ECMAScript 6 的一项特性),它非常简单:

const { a, ...rest } = { a: 1, b: 2, c: 3 };

Or with the questions sample:或者使用问题示例:

const myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
const { regex, ...newObject } = myObject;
console.log(newObject);

You can see it in action in the Babel try-out editor. 您可以在 Babel 试用版编辑器中看到它的运行情况。


Edit:编辑:

To reassign to the same variable, use a let :要重新分配给同一个变量,请使用let

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

Spread Syntax (ES6) 展开语法(ES6)

To complete Koen's answer , in case you want to remove a dynamic variable using the spread syntax, you can do it like so:要完成Koen 的回答,如果您想使用传播语法删除动态变量,您可以这样做:

 const key = 'a'; const { [key]: foo, ...rest } = { a: 1, b: 2, c: 3 }; console.log(foo); // 1 console.log(rest); // { b: 2, c: 3 }

* foo will be a new variable with the value of a (which is 1). * foo将是一个值为a (即 1)的新变量。

Extended answer 😇扩展答案😇

There are a few common ways to remove a property from an object.有几种常见的方法可以从对象中删除属性。
Each one has its own pros and cons ( check this performance comparison ):每个都有自己的优点和缺点(检查这个性能比较):

Delete Operator 删除运算符

It is readable and short, however, it might not be the best choice if you are operating on a large number of objects as its performance is not optimized.它可读且简短,但是,如果您正在对大量对象进行操作,它可能不是最佳选择,因为它的性能未优化。

delete obj[key];

Reassignment 重新分配

It is more than two times faster than delete , however the property is not deleted and can be iterated.它比delete快两倍多,但是该属性不会被删除并且可以迭代。

obj[key] = null;
obj[key] = false;
obj[key] = undefined;

Spread Operator 展开运算符

This ES6 operator allows us to return a brand new object, excluding any properties, without mutating the existing object.这个ES6运算符允许我们返回一个全新的对象,不包括任何属性,而不改变现有对象。 The downside is that it has the worse performance out of the above and is not suggested to be used when you need to remove many properties at a time.缺点是它的性能比上述更差,当您需要一次删除许多属性时,不建议使用它。

{ [key]: val, ...rest } = obj;

Another alternative is to use the Underscore.js library.另一种选择是使用Underscore.js库。

Note that _.pick() and _.omit() both return a copy of the object and don't directly modify the original object.请注意_.pick()_.omit()都返回对象的副本并且不直接修改原始对象。 Assigning the result to the original object should do the trick (not shown).将结果分配给原始对象应该可以解决问题(未显示)。

Reference: link _.pick(object, *keys)参考:链接_.pick(object, *keys)

Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys).返回对象的副本,过滤后仅包含白名单键(或有效键数组)的值。

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

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

Reference: link _.omit(object, *keys)参考:链接_.omit(object, *keys)

Return a copy of the object, filtered to omit the blacklisted keys (or array of keys).返回对象的副本,过滤以省略列入黑名单的键(或键数组)。

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

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

For arrays, _.filter() and _.reject() can be used in a similar manner.对于数组,可以以类似的方式使用_.filter()_.reject()

To clone an object without a property:克隆一个没有属性的对象:

For example:例如:

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

And we need to delete a .我们需要删除a .

  1. With an explicit prop key :使用明确的道具键

     const { a, ...rest } = object; object = rest;
  2. With a variable prop key :使用可变道具键

     const propKey = 'a'; const { [propKey]: propValue, ...rest } = object; object = rest;
  3. A cool arrow function 😎:一个很酷的箭头函数😎:

     const removeProperty = (propKey, { [propKey]: propValue, ...rest }) => rest; object = removeProperty('a', object);
  4. For multiple properties对于多个属性

    const removeProperties = (object, ...keys) => Object.entries(object).reduce((prev, [key, value]) => ({...prev, ...(!keys.includes(key) && { [key]: value }) }), {})

Usage用法

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

Or要么

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

The term you have used in your question title, Remove a property from a JavaScript object , can be interpreted in some different ways.您在问题标题中使用的术语Remove a property from a JavaScript object可以用一些不同的方式解释。 The one is to remove it for whole the memory and the list of object keys or the other is just to remove it from your object.一种是在整个内存和对象键列表中删除它,另一种是将它从您的对象中删除。 As it has been mentioned in some other answers, the delete keyword is the main part.正如在其他一些答案中提到的那样, delete关键字是主要部分。 Let's say you have your object like:假设您有这样的对象:

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

If you do:如果你这样做:

console.log(Object.keys(myJSONObject));

the result would be:结果将是:

["ircEvent", "method", "regex"]

You can delete that specific key from your object keys like:您可以从对象键中删除该特定键,例如:

delete myJSONObject["regex"];

Then your objects key using Object.keys(myJSONObject) would be:然后使用Object.keys(myJSONObject)对象键将是:

["ircEvent", "method"]

But the point is if you care about memory and you want to whole the object gets removed from the memory, it is recommended to set it to null before you delete the key:但关键是如果您关心内存并且想要将整个对象从内存中删除,建议在删除键之前将其设置为 null:

myJSONObject["regex"] = null;
delete myJSONObject["regex"];

The other important point here is to be careful about your other references to the same object.这里的另一个重点是注意对同一对象的其他引用。 For instance, if you create a variable like:例如,如果您创建一个变量,如:

var regex = myJSONObject["regex"];

Or add it as a new pointer to another object like:或者将其添加为指向另一个对象的新指针,例如:

var myOtherObject = {};
myOtherObject["regex"] = myJSONObject["regex"];

Then even if you remove it from your object myJSONObject , that specific object won't get deleted from the memory, since the regex variable and myOtherObject["regex"] still have their values.然后,即使您从对象myJSONObject删除它,该特定对象也不会从内存中删除,因为regex变量和myOtherObject["regex"]仍然具有它们的值。 Then how could we remove the object from the memory for sure?那么我们如何才能确定地从内存中删除该对象呢?

The answer would be to delete all the references you have in your code, pointed to that very object and also not use var statements to create new references to that object .答案是删除代码中所有指向该对象的引用,并且不使用var语句创建对该对象的新引用 This last point regarding var statements, is one of the most crucial issues that we are usually faced with, because using var statements would prevent the created object from getting removed.关于var语句的最后一点,是我们通常面临的最关键的问题之一,因为使用var语句会阻止创建的对象被删除。

Which means in this case you won't be able to remove that object because you have created the regex variable via a var statement, and if you do:这意味着在这种情况下,您将无法删除该对象,因为您已经通过var语句创建了regex变量,如果您这样做:

delete regex; //False

The result would be false , which means that your delete statement haven't been executed as you expected.结果将为false ,这意味着您的 delete 语句未按预期执行。 But if you had not created that variable before, and you only had myOtherObject["regex"] as your last existing reference, you could have done this just by removing it like:但是,如果您之前没有创建该变量,并且您只有myOtherObject["regex"]作为您最后一个现有引用,您可以通过删除它来完成此操作,例如:

myOtherObject["regex"] = null;
delete myOtherObject["regex"];

In other words, a JavaScript object gets killed as soon as there is no reference left in your code pointed to that object.换句话说,只要您的代码中没有指向该对象的引用,JavaScript 对象就会被杀死。


Update:更新:

Thanks to @AgentME:感谢@AgentME:

Setting a property to null before deleting it doesn't accomplish anything (unless the object has been sealed by Object.seal and the delete fails. That's not usually the case unless you specifically try).在删除之前将属性设置为 null 不会完成任何操作(除非对象已被 Object.seal 密封并且删除失败。除非您特别尝试,否则通常不会出现这种情况)。

To get more information on Object.seal : Object.seal()获取更多关于Object.seal信息: Object.seal()

ECMAScript 2015 (or ES6) came with built-in Reflect object. ECMAScript 2015(或 ES6)带有内置的Reflect对象。 It is possible to delete object property by calling Reflect.deleteProperty() function with target object and property key as parameters:可以通过使用目标对象和属性键作为参数调用Reflect.deleteProperty()函数来删除对象属性:

Reflect.deleteProperty(myJSONObject, 'regex');

which is equivalent to:这相当于:

delete myJSONObject['regex'];

But if the property of the object is not configurable it cannot be deleted neither with deleteProperty function nor delete operator:但是,如果对象的属性不可配置,则无法使用 deleteProperty 函数或 delete 运算符删除它:

let obj = Object.freeze({ prop: "value" });
let success = Reflect.deleteProperty(obj, "prop");
console.log(success); // false
console.log(obj.prop); // value

Object.freeze() makes all properties of object not configurable (besides other things). Object.freeze()使对象的所有属性都不可配置(除其他外)。 deleteProperty function (as well as delete operator ) returns false when tries to delete any of it's properties. deleteProperty函数(以及delete operator )在尝试删除它的任何属性时返回false If property is configurable it returns true , even if property does not exist.如果属性是可配置的,它返回true ,即使属性不存在。

The difference between delete and deleteProperty is when using strict mode: deletedeleteProperty的区别在于使用严格模式时:

"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

Suppose you have an object that looks like this:假设您有一个如下所示的对象:

var Hogwarts = {
    staff : [
        'Argus Filch',
        'Filius Flitwick',
        'Gilderoy Lockhart',
        'Minerva McGonagall',
        'Poppy Pomfrey',
        ...
    ],
    students : [
        'Hannah Abbott',
        'Katie Bell',
        'Susan Bones',
        'Terry Boot',
        'Lavender Brown',
        ...
    ]
};

Deleting an object property删除对象属性

If you want to use the entire staff array, the proper way to do this, would be to do this:如果你想使用整个staff数组,正确的方法是这样做:

delete Hogwarts.staff;

Alternatively, you could also do this:或者,您也可以这样做:

delete Hogwarts['staff'];

Similarly, removing the entire students array would be done by calling delete Hogwarts.students;同样,通过调用delete Hogwarts.students;delete Hogwarts.students;整个学生数组delete Hogwarts.students; or delete Hogwarts['students'];delete Hogwarts['students']; . .

Deleting an array index删除数组索引

Now, if you want to remove a single staff member or student, the procedure is a bit different, because both properties are arrays themselves.现在,如果您想删除单个教职员工或学生,过程有点不同,因为这两个属性本身都是数组。

If you know the index of your staff member, you could simply do this:如果你知道你的员工的索引,你可以简单地这样做:

Hogwarts.staff.splice(3, 1);

If you do not know the index, you'll also have to do an index search:如果您不知道索引,则还必须进行索引搜索:

Hogwarts.staff.splice(Hogwarts.staff.indexOf('Minerva McGonnagall') - 1, 1);

Note笔记

While you technically can use delete for an array, using it would result in getting incorrect results when calling for example Hogwarts.staff.length later on.虽然您在技术上可以对数组使用delete ,但在稍后调用例如Hogwarts.staff.length时,使用它会导致得到错误的结果。 In other words, delete would remove the element, but it wouldn't update the value of length property.换句话说, delete会删除元素,但不会更新length属性的值。 Using delete would also mess up your indexing.使用delete也会弄乱你的索引。

So, when deleting values from an object, always first consider whether you're dealing with object properties or whether you're dealing with array values, and choose the appropriate strategy based on that.因此,从对象中删除值时,请始终首先考虑您是在处理对象属性还是在处理数组值,然后根据此选择适当的策略。

If you want to experiment with this, you can use this Fiddle as a starting point.如果你想尝试这个,你可以使用这个 Fiddle作为起点。

我个人使用Underscore.jsLodash的对象和数组操作:

myObject = _.omit(myObject, 'regex');

Using delete method is the best way to do that, as per MDN description, the delete operator removes a property from an object.使用delete方法是最好的方法,根据 MDN 描述,delete 操作符从对象中删除一个属性。 So you can simply write:所以你可以简单地写:

delete myObject.regex;
// OR
delete myObject['regex'];

The delete operator removes a given property from an object. delete 运算符从对象中删除给定的属性。 On successful deletion, it will return true, else false will be returned.删除成功返回true,否则返回false。 However, it is important to consider the following scenarios:但是,重要的是要考虑以下情况:

  • If the property which you are trying to delete does not exist, delete will not have any effect and will return true如果您尝试删除的属性不存在,则删除不会有任何效果并返回 true

  • If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).如果对象的原型链上存在同名的属性,那么删除后,对象将使用原型链中的属性(换句话说,删除只对自己的属性有影响)。

  • Any property declared with var cannot be deleted from the global scope or from a function's scope.任何用 var 声明的属性都不能从全局作用域或函数作用域中删除。

  • As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function (expression).因此,delete 不能删除全局范围内的任何函数(无论这是函数定义的一部分还是函数(表达式)的一部分)。

  • Functions which are part of an object (apart from the作为对象一部分的函数(除了
    global scope) can be deleted with delete.全局范围)可以用 delete 删除。

  • Any property declared with let or const cannot be deleted from the scope within which they were defined.任何用 let 或 const 声明的属性都不能从定义它们的范围中删除。 Non-configurable properties cannot be removed.无法删除不可配置的属性。 This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().这包括内置对象的属性,如 Math、Array、Object 和使用 Object.defineProperty() 等方法创建为不可配置的属性。

The following snippet gives another simple example:下面的代码片段给出了另一个简单的例子:

 var Employee = { age: 28, name: 'Alireza', designation: 'developer' } console.log(delete Employee.name); // returns true console.log(delete Employee.age); // returns true // When trying to delete a property that does // not exist, true is returned console.log(delete Employee.salary); // returns true

For more info about and seeing more example, visit the link below:有关更多信息和查看更多示例,请访问以下链接:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

Using ES6: 使用ES6:

(Destructuring + Spread operator) (解构+传播运算符)

const myObject = {
    regex: "^http://.*",
    b: 2,
    c: 3
};
const { regex, ...noRegex } = myObject;
console.log(noRegex); // => { b: 2, c: 3 }

The delete operator is the best way to do so. 删除运算符是最好的方法。

A live example to show: 一个实时示例显示:

var foo = {bar: 'bar'};
delete foo.bar;
console.log('bar' in foo); // Logs false, because bar was deleted from foo.

Another solution, using Array#reduce .另一个解决方案,使用Array#reduce

 var myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; myObject = Object.keys(myObject).reduce(function(obj, key) { if (key != "regex") { //key you want to remove obj[key] = myObject[key]; } return obj; }, {}); console.log(myObject);

However, it will mutate the original object.但是,它会改变原始对象。 If you want to create a new object without the specified key, just assign the reduce function to a new variable, eg:如果你想在没有指定键的情况下创建一个新对象,只需将 reduce 函数分配给一个新变量,例如:

(ES6) (ES6)

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

There are a lot of good answers here but I just want to chime in that when using delete to remove a property in JavaScript, it is often wise to first check if that property exists to prevent errors.这里有很多很好的答案,但我只想补充一点,当使用 delete 删除 JavaScript 中的属性时,首先检查该属性是否存在以防止错误通常是明智的。

Eg例如

var obj = {"property":"value", "property2":"value"};

if (obj && obj.hasOwnProperty("property2")) {
  delete obj.property2;
} else {
  //error handling
}

Due to the dynamic nature of JavaScript there are often cases where you simply don't know if the property exists or not.由于 JavaScript 的动态特性,通常情况下您根本不知道该属性是否存在。 Checking if obj exists before the && also makes sure you don't throw an error due to calling the hasOwnProperty() function on an undefined object.在 && 之前检查 obj 是否存在还可以确保您不会因为在未定义的对象上调用 hasOwnProperty() 函数而引发错误。

Sorry if this didn't add to your specific use case but I believe this to be a good design to adapt when managing objects and their properties.抱歉,如果这没有添加到您的特定用例中,但我相信这是一个很好的设计,可以在管理对象及其属性时进行调整。

This post is very old and I find it very helpful so I decided to share the unset function I wrote in case someone else see this post and think why it's not so simple as it in PHP unset function.这篇文章很老了,我觉得它很有帮助,所以我决定分享我写的 unset 函数,以防其他人看到这篇文章并思考为什么它不像 PHP 的 unset 函数那么简单。

The reason for writing this new unset function, is to keep the index of all other variables in this hash_map.编写这个新的unset函数的原因是在这个 hash_map 中保留所有其他变量的索引。 Look at the following example, and see how the index of "test2" did not change after removing a value from the 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"}

Using ramda#dissoc you will get a new object without the attribute regex :使用ramda#dissoc您将获得一个没有属性regex的新对象:

const newObject = R.dissoc('regex', myObject);
// newObject !== myObject

You can also use other functions to achieve the same effect - omit, pick, ...您还可以使用其他功能来实现相同的效果 - 省略、选择、...

Try the following method.试试下面的方法。 Assign the Object property value to undefined .Object属性值分配给undefined Then stringify the object and parse .然后将对象stringifyparse .

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

If you want to delete a property deeply nested in the object then you can use the following recursive function with path to the property as the second argument:如果要删除深度嵌套在对象中的属性,则可以使用以下递归函数,并将该属性的路径作为第二个参数:

var deepObjectRemove = function(obj, path_to_key){
    if(path_to_key.length === 1){
        delete obj[path_to_key[0]];
        return true;
    }else{
        if(obj[path_to_key[0]])
            return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
        else
            return false;
    }
};

Example:例子:

var a = {
    level1:{
        level2:{
            level3: {
                level4: "yolo"
            }
        }
    }
};

deepObjectRemove(a, ["level1", "level2", "level3"]);
console.log(a);

//Prints {level1: {level2: {}}}

Object.assign() & Object.keys() & Array.map() Object.assign() & Object.keys() & Array.map()

 const obj = { "Filters":[ { "FilterType":"between", "Field":"BasicInformationRow.A0", "MaxValue":"2017-10-01", "MinValue":"2017-09-01", "Value":"Filters value" } ] }; let new_obj1 = Object.assign({}, obj.Filters[0]); let new_obj2 = Object.assign({}, obj.Filters[0]); /* // old version let shaped_obj1 = Object.keys(new_obj1).map( (key, index) => { switch (key) { case "MaxValue": delete new_obj1["MaxValue"]; break; case "MinValue": delete new_obj1["MinValue"]; break; } return new_obj1; } )[0]; let shaped_obj2 = Object.keys(new_obj2).map( (key, index) => { if(key === "Value"){ delete new_obj2["Value"]; } return new_obj2; } )[0]; */ // new version! let shaped_obj1 = Object.keys(new_obj1).forEach( (key, index) => { switch (key) { case "MaxValue": delete new_obj1["MaxValue"]; break; case "MinValue": delete new_obj1["MinValue"]; break; default: break; } } ); let shaped_obj2 = Object.keys(new_obj2).forEach( (key, index) => { if(key === "Value"){ delete new_obj2["Value"]; } } );

Here's an ES6 way to remove the entry easily:这是一种轻松删除条目的 ES6 方法:

 let 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", method: "newURI" }

Dan's assertion that 'delete' is very slow and the benchmark he posted were doubted. Dan 断言“删除”非常慢,他发布的基准受到质疑。 So I carried out the test myself in Chrome 59. It does seem that 'delete' is about 30 times slower:所以我自己在 Chrome 59 中进行了测试。看起来“删除”确实慢了大约 30 倍:

var iterationsTotal = 10000000;  // 10 million
var o;
var t1 = Date.now(),t2;
for (let i=0; i<iterationsTotal; i++) {
   o = {a:1,b:2,c:3,d:4,e:5};
   delete o.a; delete o.b; delete o.c; delete o.d; delete o.e;
}
console.log ((t2=Date.now())-t1);  // 6135
for (let i=0; i<iterationsTotal; i++) {
   o = {a:1,b:2,c:3,d:4,e:5};
   o.a = o.b = o.c = o.d = o.e = undefined;
}
console.log (Date.now()-t2);  // 205

Note that I purposedly carried out more than one 'delete' operations in one loop cycle to minimize the effect caused by the other operations.请注意,我特意在一个循环周期中执行了多个“删除”操作,以尽量减少其他操作造成的影响。

Property Removal in JavaScript JavaScript 中的属性删除

There are many different options presented on this page, not because most of the options are wrong—or because the answers are duplicates—but because the appropriate technique depends on the situation you're in and the goals of the tasks you and/or you team are trying to fulfill.此页面上提供了许多不同的选项,不是因为大多数选项是错误的——或者因为答案是重复的——而是因为适当的技术取决于你所处的情况以及你和/或你的任务目标团队正在努力实现。 To answer you question unequivocally, one needs to know:要明确回答您的问题,您需要知道:

  1. The version of ECMAScript you're targeting您定位的 ECMAScript 版本
  2. The range of object types you want to remove properties on and the type of property names you need to be able to omit (Strings only? Symbols? Weak references mapped from arbitrary objects? These have all been types of property pointers in JavaScript for years now)要删除属性的对象类型范围以及需要能够省略的属性名称类型(仅字符串?符号?从任意对象映射的弱引用?多年来,这些都是 JavaScript 中的属性指针类型)
  3. The programming ethos/patterns you and your team use.您和您的团队使用的编程精神/模式。 Do you favor functional approaches and mutation is verboten on your team, or do you employ wild west mutative object-oriented techniques?你喜欢函数式方法并且你的团队禁止变异,还是采用狂野西部变异的面向对象技术?
  4. Are you looking to achieve this in pure JavaScript or are you willing & able to use a 3rd-party library?您是想用纯 JavaScript 实现这一点,还是愿意并能够使用 3rd-party 库?

Once those four queries have been answered, there are essentially four categories of "property removal" in JavaScript to chose from in order to meet your goals.一旦回答了这四个查询,JavaScript 中基本上就有四类“属性删除”可供选择,以满足您的目标。 They are:他们是:

Mutative object property deletion, unsafe可变对象属性删除,不安全

This category is for operating on object literals or object instances when you want to retain/continue to use the original reference and aren't using stateless functional principles in your code.当您想要保留/继续使用原始引用并且不在代码中使用无状态功能原则时,此类别用于对对象文字或对象实例进行操作。 An example piece of syntax in this category:此类别中的示例语法:

'use strict'
const iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }
delete iLikeMutatingStuffDontI[Symbol.for('amICool')] // true
Object.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })
delete iLikeMutatingStuffDontI['amICool'] // throws

This category is the oldest, most straightforward & most widely supported category of property removal.此类别是最古老、最直接和最广泛支持的财产移除类别。 It supports Symbol & array indexes in addition to strings and works in every version of JavaScript except for the very first release.除了字符串之外,它还支持Symbol和数组索引,并且适用于除第一个版本之外的所有 JavaScript 版本。 However, it's mutative which violates some programming principles and has performance implications.但是,它是可变的,它违反了一些编程原则并具有性能影响。 It also can result in uncaught exceptions when used on non-configurable properties in strict mode . 在严格模式下用于不可配置的属性时,它也可能导致未捕获的异常。

Rest-based string property omission基于休息的字符串属性省略

This category is for operating on plain object or array instances in newer ECMAScript flavors when a non-mutative approach is desired and you don't need to account for Symbol keys:当需要非可变方法并且您不需要考虑符号键时,此类别用于在较新的 ECMAScript 风格中对普通对象或数组实例进行操作:

const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }
const { name, ...coolio } = foo // coolio doesn't have "name"
const { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(

Mutative object property deletion, safe可变对象属性删除,安全

This category is for operating on object literals or object instances when you want to retain/continue to use the original reference while guarding against exceptions being thrown on unconfigurable properties:当您想要保留/继续使用原始引用同时防止在不可配置的属性上引发异常时,此类别用于对对象文字或对象实例进行操作:

'use strict'
const iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }
Reflect.deleteProperty(iLikeMutatingStuffDontI, Symbol.for('amICool')) // true
Object.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })
Reflect.deleteProperty(iLikeMutatingStuffDontI, 'amICool') // false

In addition, while mutating objects in-place isn't stateless, you can use the functional nature of Reflect.deleteProperty to do partial application and other functional techniques that aren't possible with delete statements.此外,虽然就地改变对象不是无状态的,但您可以使用Reflect.deleteProperty的功能特性来执行部分应用和其他delete语句无法实现的功能技术。

Syntax-based string property omission基于语法的字符串属性省略

This category is for operating on plain object or array instances in newer ECMAScript flavors when a non-mutative approach is desired and you don't need to account for Symbol keys:当需要非可变方法并且您不需要考虑符号键时,此类别用于在较新的 ECMAScript 风格中对普通对象或数组实例进行操作:

const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }
const { name, ...coolio } = foo // coolio doesn't have "name"
const { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(

Library-based property omission基于图书馆的财产遗漏

This category is generally allows for greater functional flexibility, including accounting for Symbols & omitting more than one property in one statement:此类别通常允许更大的功能灵活性,包括考虑符号和在一个语句中省略多个属性:

const o = require("lodash.omit")
const foo = { [Symbol.for('a')]: 'abc', b: 'b', c: 'c' }
const bar = o(foo, 'a') // "'a' undefined"
const baz = o(foo, [ Symbol.for('a'), 'b' ]) // Symbol supported, more than one prop at a time, "Symbol.for('a') undefined"

@johnstock , we can also use JavaScript's prototyping concept to add method to objects to delete any passed key available in calling object. @johnstock ,我们还可以使用 JavaScript 的原型概念向对象添加方法,以删除调用对象中可用的任何传递键。

Above answers are appreciated.以上答案表示赞赏。

 var myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; // 1st and direct way delete myObject.regex; // delete myObject["regex"] console.log(myObject); // { ircEvent: 'PRIVMSG', method: 'newURI' } // 2 way - by using the concept of JavaScript's prototyping concept Object.prototype.removeFromObjectByKey = function(key) { // If key exists, remove it and return true if (this[key] !== undefined) { delete this[key] return true; } // Else return false return false; } var isRemoved = myObject.removeFromObjectByKey('method') console.log(myObject) // { ircEvent: 'PRIVMSG' } // More examples var obj = { a: 45, b: 56, c: 67 } console.log(obj) // { a: 45, b: 56, c: 67 } // Remove key 'a' from obj isRemoved = obj.removeFromObjectByKey('a') console.log(isRemoved); //true console.log(obj); // { b: 56, c: 67 } // Remove key 'd' from obj which doesn't exist var isRemoved = obj.removeFromObjectByKey('d') console.log(isRemoved); // false console.log(obj); // { b: 56, c: 67 }

Using Lodash使用Lodash

import omit from 'lodash/omit';

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

Using Ramda使用 Ramda

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

You can simply delete any property of an object using the delete keyword. 您可以简单地使用delete关键字delete对象的任何属性。

For example: 例如:

var obj = {key1:"val1",key2:"val2",key3:"val3"}

To remove any property, say key1 , use the delete keyword like this: 要删除任何属性,例如key1 ,请使用delete关键字,如下所示:

delete obj.key1

Or you can also use array-like notation: 或者,您也可以使用类似数组的符号:

delete obj[key1]

Ref: MDN . 参考: MDN

You can use a filter like below您可以使用如下过滤器

 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)

I have used Lodash "unset" to make it happen for a nested object also... only this needs to write small logic to get the path of the property key which is expected by the omit method.我已经使用Lodash "unset"使其也适用于嵌套对象......只需要编写小逻辑来获取omit方法预期的属性键的路径。

  1. Method which returns the property path as an array将属性路径作为数组返回的方法

 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>

  1. Then just using Lodash unset method remove property from object.然后只需使用Lodash unset方法从对象中删除属性。

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

Consider creating a new object without the "regex" property because the original object could always be referenced by other parts of your program. 考虑创建没有"regex"属性的新对象,因为原始对象始终可以被程序的其他部分引用。 Thus you should avoid manipulating it. 因此,您应该避免对其进行操作。

 const myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; const { regex, ...newMyObject } = myObject; console.log(newMyObject); 

 const myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; const { regex, ...other } = myObject; console.log(myObject) console.log(regex) console.log(other) 

You can use ES6 destructuring with rest operator. 您可以将ES6解构与rest运算符一起使用。

Properties can be removed using destructuring in combination with the rest operator . 可以通过与rest运算符结合使用分解来删除属性。 In your example regex is destructured out (ignored) and the rest of the properties are returned as rest. 在您的示例中,正则表达式被解构(忽略),其余属性作为其余部分返回。

const noRegex = ({ regex, ...rest }) => rest;
const myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

console.log(noRegex(myObjext)) //=> {  "ircEvent": "PRIVMSG","method": "newURI" }

Or you can dynamically exclude properties like this, 或者您可以动态排除此类属性,

const myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};
const removeProperty = prop => ({ [prop]: _, ...rest }) => rest

const removeRegex = removeProperty('regex') //=> {  "ircEvent": "PRIVMSG","method":"newURI" }
const removeMethod = removeProperty('method') //=> {  "ircEvent": "PRIVMSG", "regex":"^http://.*" }

尝试这个

delete myObject['key'];

Hello You Can try this simple an sort 您好,您可以尝试这种简单的排序

var obj = [];

obj.key1 = {name: "John", room: 1234};
obj.key2 = {name: "Jim", room: 1234};

delete(obj.key1);

 let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; obj = Object.fromEntries( Object.entries(myObject).filter(function (m){ return m[0] != "regex"/*or whatever key to delete*/ } )) console.log(obj)

You can also just treat the object like a2d array using Object.entries , and use splice to remove an element as you would in a normal array, or simply filter through the object, as one would an array, and assign the reconstructed object back to the original variable您也可以使用Object.entries将对象视为a2d数组,并像在普通数组中一样使用 splice 删除元素,或者像数组一样简单地过滤对象,然后将重建的对象分配回原始变量

If you don't want to modify the original object.如果不想修改原始对象。

Remove a property without mutating the object删除属性而不改变对象

If mutability is a concern, you can create a completely new object by copying all the properties from the old, except the one you want to remove.如果可变性是一个问题,您可以通过复制旧的所有属性来创建一个全新的对象,除了要删除的属性。

 let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" }; let prop = 'regex'; const updatedObject = Object.keys(myObject).reduce((object, key) => { if (key !== prop) { object[key] = myObject[key] } return object }, {}) console.log(updatedObject);

Two ways to delete an object删除对象的两种方法

  1. using for ... in使用for ... in

     function deleteUser(key) { const newUsers = {}; for (const uid in users) { if (uid !== key) { newUsers[uid] = users[uid]; } return newUsers }

or要么

delete users[key]

Say I create an object as follows:说我创建一个对象,如下所示:

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

How should I remove the property regex to end up with new myObject as follows?我应该如何删除属性regex以新的myObject结尾,如下所示?

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

Let's keep it simple, to the point:让我们保持简单,重点:

Just set that specific property/field equal to = undefined只需将该特定属性/字段设置为 = undefined

var myObject = {
    'i': "How are you?",
    'am': "Dear",
    'fine': "Hello"
};

myObject.am = undefined;

console.log(myObject);

> {i: "How are you?", am: undefined, fine: "Hello"}

There are a couple of options:有几个选项:

  1. Remove using a dot property accessor使用点属性访问器删除

 const myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*", }; delete myObject.regex; console.log(myObject);

  1. Remove using square brakets property accessor使用方形刹车属性访问器删除

 const myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*", }; delete myObject['regex']; console.log(myObject); // or const name = 'ircEvent'; delete myObject[name]; console.log(myObject);

  1. Alternative option but in an immutable manner without altering the original object, is using object destructuring and rest syntax.另一种选择,但以不改变原始对象的不可变方式,使用对象解构和休息语法。

 const myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*", }; const { regex, ...myObjectRest} = myObject; console.log(myObjectRest);

We can remove using我们可以删除使用

  1. using delete object.property使用删除 object.property
  2. using delete object['property']使用删除对象['property']
  3. using rest, remove multiple property使用休息,删除多个属性

 let myObject = { "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*", "regex1": "^http://.*", "regex2": "^http://.*", "regex3": "^http://.*", "regex4": "^http://.*" }; delete myObject.regex; // using delete object.property // Or delete myObject['regex1']; // using delete object['property'] const { regex2, regex3, regex4, ...newMyObject } = myObject; console.log(newMyObject);

您可以使用 Delete property[key] 从对象中删除属性

In JavaScript, there are 2 common ways to remove properties from an object.在 JavaScript 中,有两种常用方法可以从对象中删除属性。

The first mutable approach is to use the delete object.property operator.第一种可变方法是使用delete object.property运算符。

The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...rest} = object第二种方法是不可变的,因为它不会修改原始对象,它是调用对象解构和扩展语法: const {property, ...rest} = object

Short answer简短的回答

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

You are left with你只剩下

var obj = {
  anotherData: 'sample'    
}

 const object = { prop1: 10, prop2: 20, prop3: 30, "test prop": "This is test props" } console.log(object); // will print all 4 props delete object.prop1; delete object["test prop"]; console.log(object); // will print only prop2 and prop3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM