Home >Web Front-end >JS Tutorial >How Do I Remove a Property from a JavaScript Object?

How Do I Remove a Property from a JavaScript Object?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 10:42:10319browse

How Do I Remove a Property from a JavaScript Object?

Removing Properties from JavaScript Objects

In JavaScript, you can dynamically modify an object by adding or removing properties. This article focuses on the task of removing a specific property from an object.

Consider the following JavaScript object:

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

The goal is to remove the "regex" property from this object to obtain the following result:

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

Using the delete Keyword

To remove a property from an object, you can use the delete keyword. You can specify the property to remove in three ways:

  1. Dot Notation: delete myObject.regex
  2. Bracket Notation: delete myObject['regex']
  3. Variable: var prop = "regex"; delete myObject[prop]

Demonstration:

delete myObject.regex;

console.log(myObject); // Logs the modified object without the "regex" property

Output:

{ ircEvent: 'PRIVMSG', method: 'newURI' }

The above is the detailed content of How Do I Remove a Property from a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn