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
person
with three key-value pairs:firstName
,lastName
, andage
.We use the
delete
keyword to remove theage
key from theperson
object:delete person.age;
.We then check if the
age
key 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
person
object to the console, which will not contain theage
key 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