Skip to content

JavaScript delete object property | Example code

  • by

Use the delete operator to delete object property in JavaScript. To remove a property from an object (mutating the object), you can do it like this:

delete myObject.property;
// or

delete myObject['property'];
// or

var prop = "property";
delete myObject[prop];

Note: The delete operator deletes both the value of the property and the property itself.

JavaScript delete object property

Simple example code deleting object property using dot and bracket notations.

<!DOCTYPE html>
<html>
<body>
  <script>
   var person = {
    fName:"John",
    lName:"king",
    age:50,
    active:true
  };

  console.log(person)

  delete person.age; 
  delete person['lName'];

  console.log(person)

</script>
</body>
</html>

Output:

JavaScript delete object property

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

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

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

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

Object destructuring with rest syntax

const employee = {
  name: 'John Smith',
  position: 'Sales Manager'
};
const { position, ...employeeRest } = employee;

console.log(employeeRest); // { name: 'John Smith' }
console.log(employee); 
// { name: 'John Smith',position: 'Sales Manager' }

Do comment if you have any doubts or suggestions on this Js object topic,

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *