PASSWORD RESET

Your destination for complete Tech news

How to remove a property from a JavaScript object?

479 0
< 1 min read

To remove a property from a JavaScript object, you can use the delete operator. Here is an example:

let obj = {
  name: 'John',
  age: 30
};

delete obj.age;

console.log(obj);  // { name: 'John' }

The delete operator removes the property from the object, and the property becomes undefined.

You can also use the delete operator to remove properties from objects that are nested within other objects. For example:

let obj = {
  user: {
    name: 'John',
    age: 30
  }
};

delete obj.user.age;

console.log(obj);  // { user: { name: 'John' } }

Note that the delete operator only works on own properties of an object, and it does not affect inherited properties. If you want to remove an inherited property, you can use the Object.defineProperty method to redefine the property with a different value or with the writable attribute set to false.

let obj = {};

Object.defineProperty(obj, 'name', {
  value: 'John',
  writable: false
});

obj.name = 'Jane';  // does not modify the value of 'name'

console.log(obj.name);  // 'John'

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.