By johnstok


2008-10-16 10:57:45 8 Comments

Say I create an object as follows:

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

What is the best way to remove the property regex to end up with new myObject as follows?

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

30 comments

@Alireza 2017-04-07 16:16:01

Using delete method is the best way to do that, as per MDN description, the delete operator removes a property from an object. So you can simply write:

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

The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. 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

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

  • As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function (expression).

  • Functions which are part of an object (apart from the
    global scope) can be deleted with delete.

  • Any property declared with let or const cannot be deleted from the scope within which they were defined. 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().

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

@Bhargav Patel 2019-04-10 20:40:29

You can use ES6 destructuring with rest operator.

Properties can be removed using destructuring in combination with the rest operator. 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://.*" }

@Mythili 2019-03-13 12:31:00

As many already said you can use either "delete"(javascript property) or "unset"(using lodash).

You can also use lodash property "pick" to pick only necessary object properties.It will help when you get to delete multiple properties from the object.

Usage as below:

var _   = require("lodash");
var obj = {"a":1, "b":2, "c":3};
obj = _.pick(obj,["a","b"]);    
//Now obj contains only 2 props {"a":1, "b":2}

@emil 2016-01-22 02:29:40

I personally use Underscore.js or Lodash for object and array manipulation:

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

@Lior Elrom 2018-09-12 18:39:55

Spread Syntax (ES6)

To whoever need it...

To complete @Koen answer in this thread, in case you want to remove a dynamic variable using the spread syntax, you can do it like so:

const key = 'a';

const { [key]: foo, ...rest } = { a: 1, b: 2, c: 3 };

console.log(rest); // { b: 2, c: 3 }

* foo will be a new variable with the value of a (which is 1).


UPDATE:
There are few common ways to remove a property from an object.
Each one has it's own pros and cons (check this performance comparison):

Delete Operator
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
More than 2X faster than delete, however the property is not deleted and can be iterated.

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. The downside is that it has the worse performance out of the above and not suggested to be used when you need to remove many properties at a time.

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

@trincot 2018-12-02 20:52:15

I think the spread/rest syntax for object literals was only included in ES2018 (ES9), not ES6, even though several JS engines had already implemented it.

@Lior Elrom 2018-12-04 21:56:09

@trincot It was first introduced in 2014 (github.com/tc39/proposal-object-rest-spread) and it's a ES6 (ECMAScript 2015 aka ECMAScript 6th Edition) feature. However, even if I'm wrong, I don't think it's makes a difference to the answer's context.

@trincot 2018-12-05 07:03:19

The link refers to ES6 where indeed the spread syntax was introduced for arrays, but then it continues to propose something similar for object literals. That second part was only incorporated in ES9 if I am not mistaken.

@hossein.sharifipour 2018-11-17 19:05:51

function removeElement(elementId) {
    // Removes an element from the document
    var element = document.getElementById(elementId);
    element.parentNode.removeChild(element);
}

function addElement(parentId, elementTag, elementId, html) {
    // Adds an element to the document
    var p = document.getElementById(parentId);
    var newElement = document.createElement(elementTag);
    newElement.setAttribute('id', elementId);
    newElement.innerHTML = html;
    p.appendChild(newElement);
}

for more info click this

@ankabout 2018-11-17 19:35:45

Hi, sorry that has nothing to do with the subject :/

@Cold Cerberus 2019-02-06 02:25:26

This is not the code for removing a property from an object. The example code you provided is for removing and adding elements to the DOM.

@hygull 2018-05-24 18:42:51

@johnstock, we can also use JavaScript's prototyping concept to add method to objects to delete any passed key available in calling object.

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 }

@Braden Best 2012-09-18 00:56:53

Update 2018-07-21: For a long time, I have felt embarrassed about this answer, so I think it's time that I touch it up a little bit. Just a little commentary, clarification, and formatting to help expedite the reading of the needlessly long and convoluted parts of this answer.


THE SHORT VERSION

The actual answer to the question

As others have said, you can use delete.

obj // {"foo": "bar"}
delete obj["foo"]
obj // {}
obj["foo"] // undefined

Array equivalent

Don't delete from an array. Use Array.prototype.splice instead.

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

THE LONG VERSION

JavaScript is an OOP Language, so everything is an object, including arrays. Thus, I feel it necessary to point out a particular caveat.

In arrays, unlike plain old objects, using delete leaves behind garbage in the form of null, creating a "hole" in the array.

var array = [1, 2, 3, 4];
delete array[2];
/* Expected result --> [1, 2, 4]
 * Actual result   --> [1, 2, null, 4]
 */

As you can see, delete doesn't always work as one might expect. The value is overwritten, but the memory is not reallocated. That is to say, array[4] isn't relocated to array[3]. Which is in contrast to Array.prototype.unshift, which inserts an element in the beginning of the array and shifts everything up (array[0] becomes array[1], etc.)

Honestly, aside from setting to null rather than undefined--which is legitimately weird--this behavior shouldn't be surprising, since delete is an unary operator, like typeof, that is hard-boiled into the language and is not supposed to care about the type of object it's being used on, whereas Array is a subclass of Object with methods specifically designed for working with arrays. So there's no good reason for delete to have a special case cooked in for re-shifting the array, as that would just slow things down with unnecessary work. In retrospect, my expectations were unrealistic.

Of course, it did surprise me. Because I wrote this to justify my crusade against "null garbage":

Ignoring the dangers and problems inherent in null, and the space wasted, this can be problematic if the array needs to be precise.

Which is a terrible justification for getting rid of the nulls--null is only dangerous if used improperly, and it has nothing to do with "precision". The real reason you shouldn't delete from an array is because leaving garbage-filled and messy data structures around is sloppy and bug-prone.

What follows is a contrived scenario that gets pretty long-winded, so you can skip to the section, The Solution, if you want. The only reason I leave this section in is because I think some people probably think it's funny, and I don't want to be "that guy" who posts a "funny" answer and then deletes all the "funny" from it later on.

...It's stupid, I know.

The contrived and long-winded PDP-11 scenario

For example, say you are creating a webapp that uses JSON-serialization to store an array used for 'tabs' in a string (in this case, localStorage). Let's also say that the code uses the numerical indices of the array's members to "title" them when drawing to the screen. Why are you doing this rather than just storing the "title" as well? Because... reasons.

Okay, let's just say that you're trying to save memory at the request of this one user who runs a PDP-11 minicomputer from the 1960's running UNIX, and wrote his own Elinks-based, JavaScript-compliant, line-printer-friendly browser because X11 is out of the question.

Increasingly stupid edge-case scenario aside, using delete on said array will result in null polluting the array, and probably causing bugs in the app later on. And if you check for null, it would straight up skip the numbers resulting in the tabs being rendered like [1] [2] [4] [5] ....

if (array[index] == null)
    continue;
else
    title = (index + 1).toString();
/* 0 -> "1"
 * 1 -> "2"
 * 2 -> (nothing)
 * 3 -> "4"
 */

Yeah, that's definitely not what you wanted.

Now, you could keep a second iterator, like j, to increment only when valid values are read from the array. But that wouldn't exactly solve the null issue, and you still have to please that troll PDP-11 user. Alas, his computer just doesn't have enough memory to hold that last integer (don't ask how he manages to handle a variable-width array...).

So, he sends you an email in anger:

Hey, your webapp broke my browser! I checked my localStorage database after your stupid code made my browser segfault, and this is what I found:

>"tabs:['Hello World', 'foo bar baz', null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, ... ]"

After clearing my precious data, it segfaulted again, and I did a backtrace, and what do I find? WHAT DO I FIND!? YOU USE TOO MANY VARIABLES!

>var i = index;
>var j = 1;

Grr, I am angry now.
-Troll Davidson

About now, you're at your wit's end. This guy has been complaining non-stop about your app, and you want to tell him to shut up and go get a better computer.

The Solution: Array.prototype.splice

Luckily, arrays do have a specialized method for deleting indices and reallocating memory: Array.prototype.splice(). You could write something like this:

Array.prototype.remove = function(index){
  this.splice(index,1);
}
...
array = [1, 2, 3, 4];
array.remove(2);
// Result -> [1, 2, 4]

And just like that, you've pleased Mr. PDP-11. Hooray! (I'd still tell him off, though...)

Array.prototype.splice vs Array.prototype.slice

I feel it's important to point out the difference between these two similarly-named functions, as they are both very useful.

Array.prototype.splice(start, n)

.splice() mutates the array, and returns the removed indices. The array is sliced starting from the index, start, and n elements are sliced out. If n is unspecified, the entire array after start is sliced out (n = array.length - start).

let a = [5,4,3,2,1];
let chunk = a.splice(2,2);

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

chunk; // [3,2]
a;     // [5,4,1]

Array.prototype.slice(start, end)

.slice() is non-destructive and returns a new array containing the indicated indices from start to end. If end is left unspecified, the behavior is the same as .splice() (end = array.length). The behavior is a bit tricky since, for some reason, end indexes from 1 instead of 0. I don't know why it does this, but that's how it is. Also, if end <= start, the result is an empty array.

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

// a             [5,4,3,2,1]
// start          0 1 2 - -
// end, for...    - - - - -
//   chunks[0]  0 - - - - -   
//   chunks[1]    1 2 - - -
//   chunks[2]    1 2 3 - -
//   chunks[3]    1 2 3 4 5

chunks; // [ [], [], [3], [3,2,1] ]
a;      // [5,4,3,2,1]

That actually isn't what's happening, but it's easier to think of that way. According to MDN, here's what's actually happening:

// a             [5,4,3,2,1]
// start          0 1 2 - - -
// end, for...    - - - - - -
//   chunks[0]    0 - - - - -
//   chunks[1]    0 1 2 - - -
//   chunks[2]    0 1(2)3 - -
//   chunks[3]    0 1(2 3 4)5

The index specified by end is simply excluded from the slice. The parenthesized indices indicate what gets sliced. Either way, the behavior is not intuitive and it's bound to cause its fair share of off-by-one errors, so you might find it useful to make a wrapper function to more closely emulate the behavior of .splice():

function ez_slice(array, start = 0, n = null){
    if(!Array.isArray(array) || !is_number(start))
        return null;

    if(is_number(n))
        return array.slice(start, start + n);

    if(n === null)
        return array.slice(start);

    return null;
}

ez_slice([5,4,3,2,1], 2, 1) // [3]
ez_slice([5,4,3,2,1], 2)    // [3,2,1]

/* Fun fact: isNaN is unreliable.
 * [NaN, [], {}, 0, 1, Infinity, undefined, null, "Hi"].filter(isNaN)
 * [NaN, {}, undefined, "Hi"]
 *
 * What we want is...
 *
 * [NaN, [], {}, 0, 1, Infinity, undefined, null, "Hi"].filter(is_nan)
 * [NaN]
 */
function is_nan(num){
    return typeof num === "number"
        && num !== num;
}

function is_number(num){
    return !is_nan(num)
        && typeof num === "number"
        && isFinite(num);
}

Note that the wrapper function is designed to be very strict about types, and will return null if anything is off. That includes putting in a string like "3". It is left up to the programmer to be diligent about his types. This is to encourage good programming practice.

Update regarding is_array()

This is in regard to this (now-removed) snippet:

function is_array(array){
    return array !== null
        && typeof array === "object"
        && typeof array.length !== "undefined"
        && array.__proto__ === Array.prototype;
}

So as it turns out, there actually IS a built-in way to tell if an array is truly an array, and that is Array.isArray(), introduced in ECMAScript 5 (December 2009). I found this while looking to see if there was a question asking about telling arrays from objects, to see if there was either a better solution than mine, or to add mine if there were none. So, if you're using a version of JavaScript that is earlier than ECMA 5, there's your polyfill. However, I strongly recommend against using my is_array() function, as continuing to support old versions of JavaScript means continuing to support the old browsers that implement them, which means encouraging the use of insecure software and putting users at risk for malware. So please, use Array.isArray(). Use let and const. Use the new features that get added to the language. Don't use vendor prefixes. Delete that IE polyfill crap from your website. Delete that XHTML <!CDATA[[... crap, too--we moved to HTML5 back in 2014. The sooner everybody withdraws support for those old/esoteric browsers, the sooner the browser vendors will actually follow the web standard and embrace the new technology, and the sooner we can move on to a more secure web.

@Braden Best 2012-09-18 00:59:47

This delete keyword, however, is much more convenient, lol

@Tamas Czinege 2012-11-07 17:39:59

This approach doesn't modify the original object which might be still referenced elsewhere. This might or might not be a problem depending on how it's used but it's something to keep in mind.

@wulftone 2013-01-25 20:20:43

@B1KMusic Here's the way to delete an element from an Array: splice

@Braden Best 2013-01-26 20:37:09

@wulftone nope, that splits the array and does nothing to delete a value. I really think the best way to delete from an array where specific values are needed to be deleted is to use delete and make a Garbage Collection function to clean it up.

@wulftone 2013-01-28 19:43:54

@B1KMusic Oh I misunderstood. I thought by "delete" you meant "remove from the array." You actually mean to remove it from both the array and from memory at the same time, right?

@Braden Best 2013-01-28 22:13:38

@wulftone umm, that's kinda what I assumed delete means in general. Yes, for some of my apps, I've come across weird glitches that were caused by using just delete array[index], and I had to write my own garbage collection method to keep the array clean so it wouldn't clutter the localStorage/skip a number.

@Braden Best 2013-01-28 22:48:24

@wulftone I actually did find a use for Array.prototype.splice(). I gave my answer a much needed update

@Ry- 2013-08-27 04:01:41

I don’t see splice in your edit, but remove ought to be Array.prototype.remove = function(index) { this.splice(index, 1); };

@Braden Best 2013-09-14 04:51:27

@minitech Yeah, that would be a much smarter way of doing it. At the time of the rewrite, I had only just begun to learn about splice().

@Derek 朕會功夫 2014-06-27 18:52:25

array.splice(index, 1)....

@Patrick Roberts 2016-01-27 04:03:50

Nevermind that defining Array.prototype.remove() probably takes up much more than the approximately 8 bytes needed to define those two integers.

@Braden Best 2016-01-27 04:06:23

@PatrickRoberts JavaScript's Number type is defined as a 64-bit double, so wouldn't it be 16 bytes?

@Patrick Roberts 2016-01-27 05:47:40

@BradenBest okay sure, 16 bytes. I'm sure the function is still larger in memory.

@Braden Best 2016-01-27 05:51:06

@PatrickRoberts It's a silly, contrived scenario anyway. A retroactive excuse to justify talking about arrays in a question about objects.

@Bekim Bacaj 2016-11-16 07:34:00

This article is full of bull 1. It doesn't address the Question! 2. It is an exemplifying misuse of language and a of complain that "it doesn't work!" 3. Do not blame the JavaScript delete operator for Crockford's idiosyncratic error of putting null for an empty array index. He doesn't understand the meaning of null - he thinks it's a mistake. The mistake is his own and alone - there is no null in the deleted value of a given array index. There is no "hole" in the array - that's an empty index. Absolutely legitimate and expected.

@Braden Best 2016-11-16 19:01:42

Legitimate and expected, but not necessarily wanted, hence why I went over the splice function. And I'm not blaming anything on anything. I'm pointing out that the result of delete may not always be what you think it will, one of the many features of JavaScript that isn't quite logical.

@Braden Best 2016-11-16 19:14:10

Not that leaving a null in the array is illogical, per se. However, in a dynamic language like js, where arrays are technically objects and can be easily resized and modified, you would think delete would splice it out or throw an error. Leaving in a sentinel value is something you would do in C.

@Braden Best 2016-11-16 19:16:36

And also, you're right that I didn't directly address the question. However, this is still useful information. Useful information that is not compatible with the comment format. Hence why it is posted as an answer.

@RgSW 2017-10-25 13:31:50

On an array you can use array.splice() instead, that correctly controls the array.

@Braden Best 2017-10-26 00:32:25

@E730 you should probably read the full answer. Specifically, the implementation of Array.prototype.remove

@RgSW 2017-10-26 08:07:45

@BradenBest, you're true, but the question is about removing object properties, not array entries. Arrays are actually made for adding and removing properties, and have an API for that. Objects don't have that, so using delete will be the best answer for this question.

@Braden Best 2017-10-26 08:09:20

@E730 old news. This has already been discussed in the comments. In fact, nearly a year ago.

@Srinivas 2018-07-23 15:52:01

Using ES6:

(Destructuring + Spread operator)

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

@trincot 2018-12-02 20:53:29

I don't think this is an ES6 feature, but one that was only included in ES9.

@Srinivas 2018-12-05 05:54:00

yes, here I tried to leverage ES6 in simple steps...

@trincot 2018-12-05 07:07:42

So actually you are not using ES6, as you write, but ES9... ;-)

@redsquare 2008-10-16 11:03:01

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.

@diayn geogiev 2018-04-30 12:01:16

function removeProperty(obj, prop) {
    if(prop in obj){

    Reflect.deleteProperty(obj, prop);
    return true;
   } else {
    return false;
  }
}

@Dan 2014-02-12 17:48:05

Operator delete is unexpectedly slow!

Look at the benchmark.

Delete is the only true way to remove object's properties without any leftovers, but it works ~ 100 times slower, compared to its "alternative", setting object[key] = undefined.

This alternative is not the correct answer to this question! But, if you use it with care, you can dramatically speed up some algorithms. If you are using delete in loops and you have problems with performance, read the verbose explanation.

When should one use delete and when set value to undefined ?

An object may be seen as a set of key-value pairs. What I call a 'value' is a primitive or a reference to other object, connected to that 'key'.

Use delete, when you are passing the result object to the code on which you don't have control (or when you are not sure about your team or yourself).

It deletes the key from the hashmap.

 var obj = {
     field: 1     
 };
 delete obj.field;

Use setting to undefined, when you care about performance. It can give a serious boost to your code.

The key remains on its place in the hashmap, only the value is replaced with undefined. Understand, that for..in loop will still iterate over that key.

 var obj = {
     field: 1     
 };
 obj.field = undefined;

Using this method, not all ways of determining property existence will work as expected.

However, this code:

object.field === undefined

will behave equivalently for both methods.

Tests

To summarize, differences are all about ways of determining the property existence, and about for..in loop.

 console.log('* -> "Takes prototype inheritance into consideration, that means it lookups all over prototype chain too."');

 console.log(obj.field === undefined, 'obj.field === undefined', 'You get "undefined" value when querying for "field" in object-hashmap. *');

 console.log(obj["field"] === undefined, 'obj["field"] === undefined', 'Just another way to query (equivalent). *');

 console.log(typeof obj.field === "undefined", 'typeof obj.field === "undefined"', 'Get the value attached to "field" key, and check it\'s type is "undefined". *');

 console.log("field" in obj, '"field" in obj', 'This statement returns true if "field" key exists in the hashmap. False otherwise. *');

 console.log(obj.hasOwnProperty("field"), 'obj.hasOwnProperty("field")', 'This statement returns true if \'field\' key exists in the hashmap. The ONLY way NOT to lookup for property in the prototype chain!');
 //Object.keys().indexOf() is an overkill that runs much slower :)

 var counter = 0,
     key;
 for (key in obj) {
     counter++;
 }
 console.assert(counter === 0, 'counter === 0', '"field" is not iterated using "for .. in" loop. *');

Beware Of Memory Leaks!

While using obj[prop] = undefined is faster than doing delete obj[prop], another important consideration is that obj[prop] = undefined may not always be appropriate. delete obj[prop] removes prop from obj and erases it from memory whereas obj[prop] = undefined simply sets the value of prop to undefined which leaves prop still in memory. Therefore, in circumstances where there are many keys being created and deleted, using obj[prop] = undefined can force expensive memory reconciliation (causing the page to freeze up) and potentially an out-of-memory error. Examine the following code.

"use strict";
var theNodeList=[], i, current, numberOfNodes=65536, body=document.body, nodeRecords=[];
for (i = 0; i !== numberOfNodes; i++) {
    nodeRecords[i] = [];
    current = theNodeList[i] = document.createElement("div");
    current.textContent = i;
    document.body.appendChild( current );
}
var lastTime = -1;
requestAnimationFrame(function recordUpdates(){
    var currentTime = Math.round( performance.now()*1000 )
    for (i = 0; i !== numberOfNodes; i++) {
        if (lastTime !== -1) {
            // the previously collected data is no longer in use
            /*************************************************/
            /****/ nodeRecords[i][lastTime] = undefined; /****/
            /*************************************************/
        }
        nodeRecords[i][currentTime] = theNodeList[i].outerHTML;
    }
    lastTime = currentTime;
    requestAnimationFrame( recordUpdates );
});

In the code above, simply doing nodeRecords[i][lastTime] = undefined; will cause a massive memory leak because each animation frame. Each frame, all 65536 DOM elements will take up another 65536 individual slots, but the previous 65536 slots will only be set to undefined which leaves them hanging in the memory. Go ahead, try to run the above code in the console and see for yourself. After forcing an out-of-memory error, attempt to run it again except with the following version of the code that uses the delete operator instead.

"use strict";
var theNodeList=[], i, current, numberOfNodes=65536, body=document.body, nodeRecords=[];
for (i = 0; i !== numberOfNodes; i++) {
    nodeRecords[i] = [];
    current = theNodeList[i] = document.createElement("div");
    current.textContent = i;
    document.body.appendChild( current );
}
var lastTime = -1;
requestAnimationFrame(function recordUpdates(){
    var currentTime = Math.round( performance.now()*1000 )
    for (i = 0; i !== numberOfNodes; i++) {
        if (lastTime !== -1) {
            // the previously collected data is no longer in use
            /********************************************/
            /****/ delete nodeRecords[i][lastTime]; /****/
            /********************************************/
        }
        nodeRecords[i][currentTime] = theNodeList[i].outerHTML;
    }
    lastTime = currentTime;
    requestAnimationFrame( recordUpdates );
});

As seen in the above code snippet, there are some rare appropriate use cases for the delete operator. However, do not worry about this problem too much. This will only become a problem with long-lifespan objects that get new keys constantly added to them. In any other case (which is almost every case in real-world programming), it is most appropriate to use obj[prop] = undefined. The main purpose of this section is just to bring this to your attention so that in the rare chance that this does become a problem in your code, then you can more easily understand the problem and thus not have to waste hours dissecting your code to locate and understand this problem.

Do Not Always Set To undefined

One aspect of Javascript that is important to consider is polymorphism. Polymorphism is when assigning the same variable/slot-in-an-object different types as seen below.

var foo = "str";
foo = 100;          // variable foo is now labeled polymorphic by the browser
var bar = ["Some", "example"];
bar[2] = "text";    // bar is a monomorphic array here because all its entries have the
                    // same type: string primitive
bar[1] = undefined; // bar is now a polymorphic array

However, there are two major unfixable problems with polymorphic arrays:

  1. They are slow & memory inefficient. When accessing a specific index, instead of just getting the global type for the array, the browser instead has to get the type on a per-index basis whereby each index stores the additional metadata of its type.
  2. Once polymorphic, always polymorphic. When an array is made polymorphic, the polymorphism cannot be undone in Webkit browsers. So, even if you restore a polymorphic array to being non-polymorphic, it will still be stored by the browser as a polymorphic array.

One may liken polymorphism to a drug addiction. At first glance, it seems awesomely lucrative: nice pretty fluffy code. Then, the coder introduces their array to the drug of polymorphism. Instantly, the polymorphic array becomes less efficient, and it can never become as efficient as it was before since it is drugged. To correlate such circumstance to real life, someone on cocaine might not even be capable of operating a simple door handle, much less be able to calculate digits of PI. Likewise, an array on the drug of polymorphism cannot ever be as efficient as a monomorphic array.

But, how does a drug trip analogy relate to the delete operation? The answer inheres the last line of code in the snippet above. Thus let it be reexamined, this time with a twist.

var bar = ["Some", "example"];
bar[2] = "text";    // bar is not a polymorphic array here because all its entries have the
                    // same type: string primitive
bar[1] = "";        // bar is still a monomorphic array
bar[1] = undefined; // bar is now a polymorphic array

Observe. bar[1] = "" does not coerce polymorphism whereas bar[1] = undefined does. Therefore, one should always, whenever possible use the corresponding type for their objects so as to not accidentally cause polymorphism. One such person may use the following list as a general reference to get them going. However, please do not explicitly use the below ideas. Instead, use whatever works well for your code.

  • When using an array/variable typed to the boolean primitive, use either false or undefined as the empty value. While avoiding unnecessary polymorphism is good, rewriting all your code to explicitly forbid it will likely actually result in a decrease in performance. Use common judgement!
  • When using an array/variable typed to the number primitive, use 0 as the empty value. Note that internally, there are two types of numbers: fast integers (2147483647 to -2147483648 inclusive) and slow floating point doubles (anything other than that including NaN and Infinity). When an integer is demoted to a double, it cannot be promoted back to an integer.
  • When using an array/variable typed to the string primitive, use "" as the empty value.
  • When using a Symbol, wait, why are you using a Symbol?!?! Symbols are bad juju for performance. Everything programmed to use Symbols can be reprogrammed to not use Symbols, resulting in a faster code without Symbols. Symbols are really just super inefficient meta-sugar.
  • When using anything else, use null.

However, be mindful! Do not suddenly start doing this with all your preexisting code now as it would likely break such preexisting code and/or introduce strange bugs. Rather, such an efficient practice needs to be implemented from the start, and when converting preexisting code, it is recommended that you double, triple, quadruple check all the lines relating to that as trying to upgrade old code to this new practice can be as risky as it is rewarding.

@Lance 2014-03-04 21:05:54

a property is assigned to undefined still is a property of an object, so it will not be removed by GC, unless misread your last paragraph.

@Dan 2014-03-06 10:28:46

I was wrong to touch the theme of GC here. Both methods have the same result for GC: they remove the value linked to the key. If that value was the last reference to some other object, that object would be cleaned up.

@Benjamin Gruenbaum 2014-05-31 18:31:25

Fun fact, you can cast an object back into fast properties mode after you delete from it.

@meandre 2014-07-16 15:03:18

a property is assigned to undefined still is a property of an object, so it will not be removed by GC The GC doesn't manage anything about properties. It collects and removes values. As long as nothing references a value (an object, string, etc.) anymore, the GC does remove it from memory.

@rdllopes 2014-11-03 17:32:30

BTW, that is the dual problem to check if a property exist on Javascript object. Using in operator is the reliable but slow. Check if the property is not undefined "is not the correct answer" but it is a way faster. check

@Erik Reppen 2016-02-03 02:07:52

All I can say is test any performance assertion about JS or browsers that A. isn't about obvious work avoidance and B. is more than 5 hours old. This will probably hold for a while though. JSON parsing something you JSON stringified and then regex replaced might be one avenue to explore for performance, key-clearing, and absolutely no messy leftovers, however.

@Charlie Fish 2016-07-17 00:09:25

The delete method isn't that slow.....

@Cerbrus 2016-12-14 08:29:46

Is this answer still relevant? jsperf is currently down, but this benchmark seems to indicate that the speed difference is a mere 25%, which is nowhere close to the "~ 100 times slower" in this answer.

@Mark Giblin 2017-06-01 10:10:17

your "test" throws an error... Uncaught ReferenceError: obj is not defined

@wolfdawn 2017-07-03 12:50:09

Hi Dan, I'm no expert so I'd like to ask what you mean by "unexpectedly slow"... First it appears to run millions of times each second if I understand and I don't understand if that "test" is reliable? What do we know about the way the Browser's interpreter (or whatnot) pre-optimizes the code?

@Yin Cognyto 2017-12-25 21:54:30

Now, at the end of 2017, delete is still 98% slower than the other "alternatives" in your JSPerf test. However, when comparing things, one must use the same standards in all cases. It goes without saying that removing a property, irrespective if it's done using delete or any other function, will always be slower than assigning a value to that property, even 100 years from now. Just like removing a button from a webpage will always be slower than painting it in a transparent color - they're different operations, aka 'different standards' used for comparison...

@Hozefa 2018-01-08 18:03:26

Take every jsperf benchmark with a huge grain of salt. Most of the time the benchmark is flawed, or the difference is so minimal it won't come close to making a noticeable difference. On top of that, it's a moving target because browsers are constantly optimizing slow APIs and code patterns, so what appears slower today could get super optimized tomorrow. Best to just write code that optimizes for maintainability/deletion than worrying about micro benchmarks

@Jack Giffin 2018-04-18 00:53:54

@Hozefa Yes take them with a grain of salt if they are written as terribly as this, but no do not take them with a grain of salt if they are written durably such as to inhibit dead code elimination.

@Alejandro Vales 2018-05-29 13:22:58

Even though this answer has a lot of upvotes THIS answer to THIS question is a complete mistake in my opinion. Even though delete is slow, it is the correct answer to the question, because reasigning the property to be undefined wouldn't actually delete the property, therefore not answering the question

@Vitim.us 2019-03-05 22:29:10

This answer is inaccurate in many points, delete does not clear memory, it in fact removes the reference, so does assigning any other value to the property. Garbage collector may or may not free the old memory. Removing the property and assigning undefined have different semantics.

@RITESH ARORA 2018-03-08 09:52:19

For

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

delete myObject["regex"]; Also you know index of key , for Eg. You need to delete 2nd key(regex) then

var key =  Object.keys(myObject)[2]
delete myObject[key];

Many time we require index based removing in object But Remember keys in object may be up-down position so please careful during using it

@xiang 2018-02-06 04:28:57

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

const { regex, ...other } = myObject;

console.log(myObject)
console.log(regex)
console.log(other)

@Thaddeus Albers 2014-05-24 18:53:26

Another alternative is to use the Underscore.js library.

Note that _.pick() and _.omit() both return a copy of the object and don't directly modify the original object. Assigning the result to the original object should do the trick (not shown).

Reference: link _.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)

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.

@Jordan Arseno 2014-12-09 01:32:19

Keep in mind that if your object's keys are numbers, you may need to _.omit(collection, key.toString())

@Jack Giffin 2018-04-14 23:00:57

Hmmmmm.... Underscore is ~100x slower than delete obj[prop] which is ~100x slower than obj[prop] = undefined.

@james_womack 2017-12-14 02:35:29

Property Removal in 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
  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)
  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?

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

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.

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:

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"

@xgqfrms-gildata 2017-09-19 08:37:41

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"];
        }
    }
);

@xgqfrms-gildata 2017-09-19 08:38:03

@kind user 2017-03-26 15:19:55

Another solution, using 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, e.g.:

(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);

@ideaboxer 2017-10-23 10:06:31

Consider creating a new object without the "regex" property because the original object could always be referenced by other parts of your program. Thus you should avoid manipulating it.

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

const { regex, ...newMyObject } = myObject;

console.log(newMyObject);

@Krzysztof Przygoda 2018-04-03 20:24:59

SyntaxError: Unexpected token '...'. Expected a property name.?

@ideaboxer 2018-04-03 20:45:04

Try it with a modern browser such as Firefox, Chromium or Safari. And I expect it to work with Edge as well.

@ideaboxer 2018-04-03 20:48:37

As an alternative, if your customers force you to support outdated browsers, you could consider using TypeScript which transpiles your code into legacy syntax (+ gives you the benefit of static type safety).

@MANISH MOHAN 2017-10-13 09:40:07

you can use the delete operator as of below.

 var multiverse = {
        earth1: "Silver Age",
        earth2: "Golden Age"
    };

delete multiverse.earth2;//will return true if it finds 

// Outputs: { earth1: "Silver Age" }
console.log(multiverse);

The delete operator also has a return value. If it succeeds in deleting a property, it will return true. If it fails to delete a property because the property is unwritable it will return false, or if in strict mode it will throw an error.

@nickf 2008-10-16 10:58:53

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.

@johnstok 2008-10-16 11:04:14

Is it possible to use associative array syntax with delete? Say i have the name of the property as a string i.e. 'regex'.

@johnstok 2008-10-16 11:06:42

Checked, it also works with "delete myJSONObject['regex'];" See: developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…

@AnthonyWJones 2008-10-16 12:41:45

Irritatingly MS fail to mention that in their own JScript documentation on MSDN.

@George Jempty 2010-04-16 16:24:33

An upshot of one of the observations at the "understanding delete" link above, is that, since you cannot necessarily delete a variable, but only object properties, you therefore cannot delete an object property "by reference" -- var value=obj['prop']; delete value //doesn't work

@Doug Molineux 2011-08-10 02:21:35

So it doesn't actually delete it? It just becomes undefined, but the key still exists? Am I missing something?

@nickf 2011-08-10 08:29:19

@Pete no, it does remove it. Given: var x = {a : 'A', b : 'B'}; Compare: delete x.a; typeof x.a; /* "undefined" */ x.hasOwnProperty('a'); /* false */ to x.b = undefined; typeof x.b; /* "undefined" */; x.hasOwnProperty('b'); /* true */

@Resist Design 2012-07-28 09:22:43

I'm finding that I get an error when using Object.defineProperty( window, "b", ... ) on a var that was already declared on window, for example: "var b = 500;" even if I delete it, the error reads: "Uncaught TypeError: Cannot redefine property: b". (Latest version of Chrome.)

@Patrick M 2012-10-26 22:03:04

It's worth noting that you can use the 3rd example given here to delete items inside of a for-in loop. for(var k in obj) { delete obj[k]; } will unset every property of the object (not that you'd ever have a use for this, specifically -- but you could add a condition, like if (obj[k] === 2)).

@nickf 2012-12-20 01:57:12

@ChristopherPfohl works for me. Like I said, it's actually quite in-depth, so it's a bit difficult to summarize. The basic response in the answer above is sufficient for almost all cases, the blog goes into some more of the edge cases and the reasons those cases exist.

@Jacob Relkin 2013-07-09 20:07:16

@GeorgeJempty You can use a variable for the property name itself in the delete expression: var x = 'x'; delete object[x];

@Cfreak 2014-05-05 19:20:58

I know this is old but I ran into a gotcha after using delete and then checking an object with jquery's .isEmptyObject the function will return false.

@nickf 2014-05-22 16:42:54

@geoidesic it's not an array, it's an object. If you want to remove an item from an array, you should use .splice()

@code ninja 2014-08-29 16:15:11

isn't delete forbidden when using JS Strict mode? doc on strict mode. How could I delete the property when using strict mode?

@code ninja 2014-08-29 16:22:29

Question for my comment above: stackoverflow.com/questions/25572222/… thanks

@iabw 2014-09-03 13:08:05

It's possible for deleting keys from an object to actually slow it down, if the Javascript engine is optimizing memory. Addy Osmani talks about it in a couple different places.

@Matthew Strawbridge 2016-06-02 11:09:06

If you delete a property from an object and wonder why it's still there, it's probably picking it up from the prototype (although browser implementation varies).

@amn 2018-11-06 15:53:54

To understand how delete works, I can recommend reading on its function equivalent, Reflect.deleteProperty -- both perform exactly the same operation, but the function may be a bit more understandable.

@BEJGAM SHIVA PRASAD 2017-09-29 08:03:10

I have used lodash "unset" to make it happen for nested object also.. only this need to write small logic to get path of property key which expected by omit method.

  1. Method which returns property path as 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.

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

@johndavedecano 2017-09-14 14:14:07

Using 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

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

@Chong Lip Phang 2017-07-26 07:19:30

Dan's assertion that 'delete' is very slow and the benchmark he posted were doubted. So I carried out the test myself in Chrome 59. It does seem that 'delete' is about 30 times slower:

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.

@Behnam Mohammadi 2017-07-09 12:51:56

Very simple:

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

delete myObject.regex;

@Dhaval Gohel 2017-05-26 09:28:09

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);

@codemirror 2017-05-26 06:58:29

Try this

delete myObject['key'];

@Koen. 2016-11-08 18:02:09

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);

@Vingt_centimes 2016-12-01 17:14:04

Maybe because the goal is to remove a property from an object, not to create a new one without the property... although, your solution is my favorite, as I prefer the immutable way.

@Koen. 2016-12-01 20:45:31

The question stated "to end up with new myObject".

@Justin C 2016-12-21 01:59:38

According to kangax.github.io/compat-table/esnext, object rest properties aren't finalized for ES6, have zero browser implementations, and only Babel provides support.

@Magnus Wolffelt 2017-06-30 07:24:43

Also I consider this approach less readable than some alternatives. This is basically a hack using destructuring assignment and rest operator to achieve something which is not immediately apparent to the reader. In contrast, the delete statement or the Underscore way of _.omit are both quite obvious with regards to intent.

@Magnus Wolffelt 2017-06-30 07:26:07

Plus you litter your scope with the regex variable in this example.

@Koen. 2017-06-30 07:30:00

Adding Underscore for removing a property will litter your project :) Instead of having it available as regex you could also assign it to any other variable, e.g. _, what is used in languages like Go to discard a result: const { regex: _, ...newObject } = myObject;.

@Damaged Organic 2017-07-01 18:51:14

This is actually a sweet one-liner for new object assignment without unwanted props, and already supported with Node.js 8.*/9.* with --harmony: node.green/…

@Pranay Kumar 2018-05-03 02:08:43

what if regex is variable which holds the key?

@Koen. 2018-05-03 11:06:02

@PranayKumar I was hoping this syntax would work; const { [key], ...newObject } = myObject; but it doesn't, so I don't think it's possible with destructuring.

@Braden Best 2018-08-03 05:45:22

With freeze()'d and seal()'d objects, you can't simply delete a property. So this is an excellent alternative. Although in most cases, it probably won't make sense to delete a property from a frozen/sealed object anyway, considering that the whole point is to make certain guarantees about your data structures, of which this pattern would be undermining. For those cases where you need to non-destructively dupe an object but without some of its properties, this is perfect

@Vitim.us 2019-03-05 22:32:06

This is creating a whole new object, be aware that this will break inheritance, instanceof operator.

@Amio.io 2016-11-28 15:14:52

Using ramda#dissoc you will get a new object without the attribute regex:

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

You can also use other functions to achieve the same effect - omit, pick, ...

@John Slegers 2016-02-21 18:09:47

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:

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; or 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. In other words, delete would remove the element, but it wouldn't update the value of length property. Using delete would also mess up your indexing.

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.

@Joel Trauger 2016-09-22 15:30:26

I would think you should always use splice on an array instead of delete.

@John Slegers 2016-11-23 09:19:15

@JoelTrauger : That's what I'm saying ;-)

@Joel Trauger 2016-11-23 21:59:56

Yes. My comment is that that delete shouldn't even be a thing. It's splice is what the OP was looking for.

@John Slegers 2016-11-24 10:01:08

@JoelTrauger : As I tried to explain, delete should be used for object properties and splice for array elements.

@Jack Giffin 2018-04-14 23:05:43

Splice is really slow. While it should be used instead of delete on arrays, it would be wisest to not create code centered around it at all.

@John Slegers 2018-04-15 16:36:36

@lolzerywowzery : What strategy would you suggest for removing elements from an array without using splice?

@Jack Giffin 2018-04-30 14:41:59

@JohnSlegers It really depends on the code at hand. In general I would say try to create code organized to have arrays that push/pop items on them or arrays that contain data where the data is modified, not the array, instead of using splice.

@John Slegers 2018-04-30 16:18:29

@lolzerywowzery : Sure. If the order of the items in your array is not important, you could use tricks like popping the last element off an array and then replacing the element you want to remove with the element you just popped. However, that only works if the order of your elements is not important. If you need to preserve the order, I can't think of a good alternative to splice.

@Jack Giffin 2018-05-02 23:01:57

@JhonSleigers True, true. On small data sets splice is good and rational. On large data sets such as text editors, well, there inlies what separates the best programmers from the good programmers. A good programmer would just tell their boss its impossible to have better performance. The best programmer would figure out an alternative way to store the data for those circumstances to provide fast insertion and deletion without sacrificing the speed at which that data is specifically accessed.

Related Questions

Sponsored Content

70 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

78 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5650464 View
  • 7025 Score
  • 78 Answer
  • Tags:   javascript arrays

3 Answered Questions

60 Answered Questions

[SOLVED] How can I merge properties of two JavaScript objects dynamically?

36 Answered Questions

[SOLVED] Length of a JavaScript object

20 Answered Questions

86 Answered Questions

[SOLVED] How do JavaScript closures work?

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

16 Answered Questions

[SOLVED] How to list the properties of a JavaScript object?

  • 2008-10-16 10:08:18
  • johnstok
  • 672771 View
  • 767 Score
  • 16 Answer
  • Tags:   javascript

26 Answered Questions

[SOLVED] Storing Objects in HTML5 localStorage

Sponsored Content