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"
};
share|improve this question

31 Answers 31

up vote 6338 down vote accepted

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.

share|improve this answer
  • 20
    Checked, it also works with "delete myJSONObject['regex'];" See: developer.mozilla.org/en/Core_JavaScript_1.5_Reference/… – johnstok Oct 16 '08 at 11:06
  • 77
    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 – George Jempty Apr 16 '10 at 16:24
  • 13
    So it doesn't actually delete it? It just becomes undefined, but the key still exists? Am I missing something? – Doug Molineux Aug 10 '11 at 2:21
  • 103
    @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 */ – nickf Aug 10 '11 at 8:29
  • 9
    @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. – nickf Dec 20 '12 at 1:57

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

 var counter = 0,
     key;
 for (key in obj) {
     counter++;
 }
 console.assert(counter === 0, 'counter === 0', '"field" is not iterated using "for .. in" loop. *');
share|improve this answer
  • 27
    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. – Lance Mar 4 '14 at 21:05
  • 4
    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. – Dan Mar 6 '14 at 10:28
  • 7
    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. – meandre Jul 16 '14 at 15:03
  • 4
    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 – rdllopes Nov 3 '14 at 17:32
  • 11
    The question is "How do I remove a property from the Object" - Not the Value. – Bekim Bacaj Jun 12 '16 at 20:49

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

console.log ( myJSONObject.regex); // logs: undefined

This works in Firefox and Internet Explorer, and I think it works in all others.

share|improve this answer

As others have said, you can use delete. But JavaScript is an OOP Language, so everything is an object. 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.

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

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.

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

share|improve this answer
  • 14
    This delete keyword, however, is much more convenient, lol – Braden Best Sep 18 '12 at 0:59
  • 9
    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. – Tamas Czinege Nov 7 '12 at 17:39
  • 15
    @B1KMusic Here's the way to delete an element from an Array: splice – wulftone Jan 25 '13 at 20:20
  • 1
    @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. – Braden Best Jan 26 '13 at 20:37
  • 4
    I don’t see splice in your edit, but remove ought to be Array.prototype.remove = function(index) { this.splice(index, 1); }; – Ryan Aug 27 '13 at 4:01

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);
share|improve this answer

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.

share|improve this answer

The term you have used in your question title Remove a property from a JavaScript object, can be interpreted in some different ways. 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. 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:

["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:

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

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:

delete regex; //False

The result would be false, which means that your delete statement haven't been executed as you expected. 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"] = 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.


Update: Thanks to @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).

To get more info on Object.seal: Object.seal()

share|improve this answer
  • You're wrong - only objects are passed by reference in JavaScript, so if myJSONObject.regex's value is a string and you assign it to some other object, the other object has a copy of this value. – Michał Perłakowski Jan 10 '16 at 16:58
  • You are right and this is a quote: "to be careful about your other references to the same object." – Mehran Hatami Jan 10 '16 at 17:34

ECMAScript 2015 (or ES6) came with built-in Reflect object. It is possible to delete object property by calling Reflect.deleteProperty() function with target object and property key as parameters:

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:

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). deleteProperty function (as well as delete operator) returns false when tries to delete any of it's properties. If property is configurable it returns true, even if property does not exist.

The difference between delete and deleteProperty is when using strict mode:

"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
share|improve this answer
  • 1
    @Gothdo it has more benefits, especially when you need to do some functional stuff. E.g. you can assign function to variable, pass as an argument or use apply, call, bind functions... – madox2 Jan 10 '16 at 16: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.

share|improve this answer

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.
share|improve this answer

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

myObject = _.omit(myObject, 'regex');
share|improve this answer

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.

The reason for writing this new unset function, is to keep the index of all other variables in this 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.

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"}
share|improve this answer

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

share|improve this answer

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.

E.g

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

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.

share|improve this answer
  • 2
    delete foo.bar works even if bar doesn't exist, so your test is a bit too much, IMHO. – PhiLho Jun 1 '15 at 15:14
  • @PhiLho that depends on where you are running JavaScript. In Node.js I believe this causes your server to crash. – Willem Jun 2 '15 at 20:07
  • 2
    delete foo.bar; only throws an exception if foo is falsy, or if you're in strict mode and foo is an object with an unconfigurable bar property. – AgentME Jun 2 '15 at 21:28
  • I don't remember the exact issue I've had with this but I think the problem may appear when foo itself doesn't exist and you try to delete it's property. – Willem Jun 2 '15 at 22:20
  • Yes, you have to test if foo exists, otherwise foo.bar will throw an exception, but you don't need to check the existence for bar before deleting it. That's the "too much" part of my comment. :-) – PhiLho Jun 3 '15 at 9:16

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

share|improve this answer

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: {}}}
share|improve this answer
  • This function works like a charm, but why do we need return true and return false? My version of the code: codepen.io/anon/pen/rwbppY. Will my version fail for any case? – novembersky Jul 17 '17 at 0:07
  • @witty2017 it won't fail. The place where I used the function also needed to check whether the property already exists or not. if the property doesn't exist, it'll return false. If it finds the property and deletes it, it'll return true. – ayushgp Jul 17 '17 at 5:52

Try the following method. Assign the Object property value to undefined. Then stringify the object and parse.

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

myObject.regex = undefined;
myObject = JSON.parse(JSON.stringify(myObject));

console.log(myObject);

share|improve this answer

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: 'abc',
  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

share|improve this answer

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.

share|improve this answer

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

share|improve this answer

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

share|improve this answer

You can simply delete any property of an object using the delete keyword.

For example:

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

To remove any property, say key1, use the delete keyword like this:

delete obj.key1

Or you can also use array-like notation:

delete obj[key1]

Ref: MDN.

share|improve this answer

Try this

delete myObject['key'];
share|improve this answer

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);
share|improve this answer

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}
share|improve this answer

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.

share|improve this answer

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"
share|improve this answer

Very simple:

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

delete myObject.regex;
share|improve this answer

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

share|improve this answer

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

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

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

share|improve this answer

protected by Jason McCreary Oct 20 '11 at 18:27

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.