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

How Do I Delete a Property from a JavaScript Object?

DDD
DDDOriginal
2024-12-24 02:01:14129browse

How Do I Delete a Property from a JavaScript Object?

Deleting a Property from a JavaScript Object

In JavaScript, objects are collections of key-value pairs. Deleting a property from an object removes the key-value pair associated with that property.

How to Delete a Property

There are several ways to delete a property from an object:

  • Using delete keyword: The delete keyword removes the specified property from the object.
delete myObject.regex; // Remove "regex" property
  • Using square brackets (ES3 ): You can also use square brackets to delete a property.
delete myObject['regex']; // Remove "regex" property
  • Using a variable (ES6 ): You can store the property name in a variable and then use that variable to delete the property.
const prop = "regex";
delete myObject[prop]; // Remove "regex" property

Example

Given the following object:

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

To remove the "regex" property and end up with the following object:

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

You can use the following code:

delete myObject.regex;

console.log(myObject); // Outputs: {ircEvent: "PRIVMSG", method: "newURI"}

The above is the detailed content of How Do I Delete 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