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
Release: 2024-12-24 02:01:14
Original
179 people have browsed it

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
Copy after login
  • Using square brackets (ES3 ): You can also use square brackets to delete a property.
delete myObject['regex']; // Remove "regex" property
Copy after login
  • 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
Copy after login

Example

Given the following object:

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

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

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

You can use the following code:

delete myObject.regex;

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template