To remove a property from a JavaScript object, you can use the delete
operator.
Here’s an example of how you can use the delete
operator to remove a property from an object:
const obj = { name: 'John', age: 30 }; delete obj.name; console.log(obj); // { age: 30 }
This will remove the name
property from the obj
object.
You can also use the delete
operator to remove properties from nested objects:
const obj = { name: 'John', age: 30, address: { street: '123 Main St', city: 'New York' } }; delete obj.address.city; console.log(obj); // { name: 'John', age: 30, address: { street: '123 Main St' } }
Keep in mind that the delete
operator only removes the property from the object, and does not change the object’s prototype. If you want to remove the property from the object’s prototype as well, you can use the Object.defineProperty
method to redefine the property with a configurable
attribute set to true
.
const obj = { name: 'John', age: 30 }; Object.defineProperty(obj, 'name', { configurable: true, value: undefined }); delete obj.name; console.log(obj); // { age: 30 }
This will remove the name
property from both the object and its prototype.