Skip to main content

In Node.js, you can remove a property or key from an object using the `delete` keyword.

Here's an example:

const myObj = {
  name: 'John',
  age: 30,
  city: 'New York'
};

delete myObj.city;

console.log(myObj);
// Output: { name: 'John', age: 30 }

In this example, we create an object `myObj` with three properties: `name`, `age`, and `city`. We then use the `delete` keyword to remove the `city` property from the object. Finally, we log the object to the console to verify that the `city` property has been removed.

You can also remove a property using a variable as the key name, like this:

const myObj = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const keyToRemove = 'city';
delete myObj[keyToRemove];

console.log(myObj);
// Output: { name: 'John', age: 30 }

In this example, we create a variable `keyToRemove` that contains the name of the property we want to remove (`city`). We then use this variable to access the property using bracket notation (`myObj[keyToRemove]`) and remove it using the `delete` keyword.

Note that if you try to remove a property that doesn't exist on the object, no error will be thrown, and the object will remain unchanged.