You can remove a key from a JavaScript object using the delete keyword. Here's how you can do it with an example:
javascript
// Create an example object
var person = {
firstName: "John",
lastName: "Doe",
age: 30,
};
// Remove the 'age' key from the object
delete person.age;
// Check if the 'age' key is gone
if (!person.age) {
console.log("The 'age' key has been removed.");
} else {
console.log("The 'age' key is still present.");
}
// Print the updated object
console.log(person);
In this example:
We create an object named
personwith three key-value pairs:firstName,lastName, andage.We use the
deletekeyword to remove theagekey from thepersonobject:delete person.age;.We then check if the
agekey is still present in the object usingif (!person.age). If it's not present, we print a message indicating that it has been removed.Finally, we print the updated
personobject to the console, which will not contain theagekey anymore.
When you run this code, you'll see that the age key is removed from the person object, and the output will confirm this.
Comments
Post a Comment