How do I remove a property from a JavaScript object?

How do I remove a property from a JavaScript object?
How do I remove a property from a JavaScript object?

To delete a property from a JavaScript object, you can use the delete operator.

For example:

let obj = {
  key1: 'value1',
  key2: 'value2'
};

delete obj.key1;

console.log(obj);  // { key2: 'value2' }

This will remove the key1 property from the obj object.

Note that the delete operator only works on own properties of an object, and not on properties inherited from the object’s prototype.

If you want to remove a property from an object and all of its prototypes, you can use the delete operator in combination with the in operator, like this:

let obj = {
  key1: 'value1'
};

let obj2 = Object.create(obj);

delete obj2.key1;  // This will delete the property from obj2, but not from obj

console.log(obj2.key1);  // undefined
console.log(obj.key1);   // 'value1'

delete obj2.key1 in obj;  // This will delete the property from obj and all of its prototypes

console.log(obj2.key1);  // undefined
console.log(obj.key1);   // undefined

Leave a Reply