How do I remove a property from a JavaScript object?

Viewed 2878751

Given an object:

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

How do I remove the property regex to end up with the following myObject?

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

To remove a property from an object (mutating the object), you can do it like this:

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

Demo

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

console.log(myObject);

For anyone interested in reading more about it, Stack Overflow user kangax has written an incredibly in-depth blog post about the delete statement on their blog, Understanding delete. It is highly recommended.

If you'd like a new object with all the keys of the original except some, you could use destructuring.

Demo

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

// assign the key regex to the variable _ indicating it will be unused
const {regex: _, ...newObj} = myObject;

console.log(newObj);   // has no 'regex' key
console.log(myObject); // remains unchanged

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.

Spread Syntax (ES6)

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

const key = 'a';

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

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

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

Extended answer

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

Delete Operator

It is readable and short, however, it might not be the best choice if you are operating on a large number of objects as its performance is not optimized.

delete obj[key];

Reassignment

It is more than two times faster than delete, however the property is not deleted and can be iterated.

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 is not suggested to be used when you need to remove many properties at a time.

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

To clone an object without a property:

For example:

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

And we need to delete a.

  1. With an explicit prop key:

    const { a, ...rest } = object;
    object = rest;
    
  2. With a variable prop key:

    const propKey = 'a';
    const { [propKey]: propValue, ...rest } = object;
    object = rest;
    
  3. A cool arrow function :

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

    const removeProperties = (object, ...keys) => (keys.length ? removeProperties(removeProperty(keys.pop(), object), ...keys) : object);
    

Usage

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

Or

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

There are a couple of ways to remove properties from an object:

  1. Remove using a dot property accessor

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

delete myObject.regex;
console.log(myObject);

  1. Remove using square brackets property accessor

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

delete myObject['regex'];
console.log(myObject);
// or
const name = 'ircEvent';
delete myObject[name];
console.log(myObject);

  1. Alternative option but in an immutable manner without altering the original object, is using object destructuring and rest syntax.

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

const { regex, ...myObjectRest} = myObject;
console.log(myObjectRest); 

Here's an ES6 way to remove the entry easily:

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

const removeItem = 'regex';

const { [removeItem]: remove, ...rest } = myObject;

console.log(remove); // "^http://.*"
console.log(rest); // Object { ircEvent: "PRIVMSG", method: "newURI" }

You can use a filter like below

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

// Way 1

let filter1 = {}
  Object.keys({...myObject}).filter(d => {
  if(d !== 'regex'){
    filter1[d] = myObject[d];
  }
})

console.log(filter1)

// Way 2

let filter2 = Object.fromEntries(Object.entries({...myObject}).filter(d =>
d[0] !== 'regex'
))

console.log(filter2)

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

  1. Method which returns the property path as an array

var a = {"bool":{"must":[{"range":{"price_index.final_price":{"gt":"450", "lt":"500"}}}, {"bool":{"should":[{"term":{"color_value.keyword":"Black"}}]}}]}};

function getPathOfKey(object,key,currentPath, t){
    var currentPath = currentPath || [];

    for(var i in object){
        if(i == key){
            t = currentPath;
        }
        else if(typeof object[i] == "object"){
            currentPath.push(i)
            return getPathOfKey(object[i], key,currentPath)
        }
    }
    t.push(key);
    return t;
}
document.getElementById("output").innerHTML =JSON.stringify(getPathOfKey(a,"price_index.final_price"))
<div id="output">

</div>

  1. Then just using Lodash unset method remove property from object.

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

@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 }

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


obj = Object.fromEntries(
    Object.entries(myObject).filter(function (m){
        return m[0] != "regex"/*or whatever key to delete*/
    }
))

console.log(obj)

You can also just treat the object like a2d array using Object.entries, and use splice to remove an element as you would in a normal array, or simply filter through the object, as one would an array, and assign the reconstructed object back to the original variable

If you don't want to modify the original object.

Remove a property without mutating the object

If mutability is a concern, you can create a completely new object by copying all the properties from the old, except the one you want to remove.

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

let prop = 'regex';
const updatedObject = Object.keys(myObject).reduce((object, key) => {
  if (key !== prop) {
    object[key] = myObject[key]
  }
  return object
}, {})

console.log(updatedObject);

Two ways to delete an object

  1. using for ... in

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

or

delete users[key]

We can remove using

  1. using delete object.property
  2. using delete object['property']
  3. using rest, remove multiple property

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

delete myObject.regex; // using delete object.property

// Or 

delete myObject['regex1']; // using delete object['property']

const { regex2, regex3, regex4, ...newMyObject } = myObject;

console.log(newMyObject);

You can delete property from object using Delete property[key]

In JavaScript, there are 2 common ways to remove properties from an object.

The first mutable approach is to use the delete object.property operator.

The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...rest} = object

Short answer

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

You are left with

var obj = {
  anotherData: 'sample'    
}
Related