Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove properties from objects (JavaScript)

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?

let myObject = {   "ircEvent": "PRIVMSG",   "method": "newURI" }; 
like image 534
johnstok Avatar asked Oct 16 '08 10:10

johnstok


People also ask

How do I remove all properties of an object?

Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!

How do I remove a property name from an object?

The delete operator is used to remove these keys, more commonly known as object properties, one at a time. 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.


1 Answers

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. It is highly recommended.

If you'd like a new object with all the keys of the original except some, you could use 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
like image 182
nickf Avatar answered Sep 18 '22 23:09

nickf