How do I remove a property from a JavaScript object?

ID : 121290

viewed : 30

Tags : javascriptobjectooppropertiesjavascript

Top 5 Answer for How do I remove a property from a JavaScript object?

vote vote

91

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

vote vote

83

Objects in JavaScript can be thought of as maps between keys and values. The delete operator is used to remove these keys, more commonly known as object properties, one at a time.

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. 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.

vote vote

70

Old question, modern answer. Using object destructuring, an ECMAScript 6 feature, it's as simple as:

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.


Edit:

To reassign to the same variable, use a let:

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

65

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.

vote vote

58

The delete operator is used to remove properties from objects.

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. For example:

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

Details

Strictly speaking, it's impossible to truly delete anything in JavaScript. The delete operator neither deletes objects nor frees memory. Rather, it sets its operand to undefined and manipulates the parent object so that the member is gone.

let parent = {     member: { str: "Hello" } }; let secondref = parent.member;  delete parent.member; parent.member;        // undefined secondref;            // { str: "Hello" } 

The object is not deleted. Only the reference is. Memory is only freed by the garbage collector when all references to an object are removed.

Another important caveat is that the delete operator will not reorganize structures for you, which has results that can seem counterintuitive. Deleting an array index, for example, will leave a "hole" in it.

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

This is because arrays are objects. So indices are the same as keys.

let fauxarray = {0: 1, 1: 2, length: 2}; fauxarray.__proto__ = [].__proto__; fauxarray.push(3); fauxarray;                // [1, 2, 3] Array.isArray(fauxarray); // false Array.isArray([1, 2, 3]); // true 

Different built-in functions in JavaScript handle arrays with holes in them differently.

  • for..in statements will skip the empty index completely.

  • A naive for loop will yield undefined for the value at the index.

  • Any method using Symbol.iterator will return undefined for the value at the index.

  • forEach, map and reduce will simply skip the missing index, but will not remove it

Example:

let array = [1, 2, 3]; // [1,2,3] delete array[1];       // [1, empty, 3] array.map(x => 0);     // [0, empty, 0] 

So, the delete operator should not be used for the common use-case of removing elements from an array. Arrays have a dedicated methods for removing elements and reallocating memory: Array#splice() and Array#pop.

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

Array#splice mutates the array, and returns any removed indices. deleteCount elements are removed from index start, and item1, item2... itemN are inserted into the array from index start. If deleteCount is omitted then elements from startIndex are removed to the end of the array.

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#slice([begin[, end]])

Array#slice is non-destructive, and returns a new array containing the indicated indices from start to end. If end is left unspecified, it defaults to the end of the array. If end is positive, it specifies the zero-based non-inclusive index to stop at. 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). If end <= start, the result is an empty array.

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

Array#pop removes the last element from an array, and returns that element. This operation changes the length of the array. The opposite operation is push

Array#shift

Array#shift is similar to pop, except it removes the first element. The opposite operation is unshift.

Top 3 video Explaining How do I remove a property from a JavaScript object?

Related QUESTION?