I am trying to delete a object property which is shallow copy of another object. But the problem arises when I try to delete it, it never goes off while original value throws expected output.
var obj = {
name:"Tom"
};
var newObj = Object.create(obj);
delete newObj.name;//It never works!
console.log(newObj.name);//name is still there
Remove a Property from a JS Object with the Delete Operator delete object. property; delete object['property'];
Remove Property from an ObjectThe delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.
In JavaScript, there are 2 common ways to remove properties from an object. The first mutable approach is to use the delete object. property operator. The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...
Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.
newObj
inherits from obj
.
You can delete the property by accessing the parent object:
delete Object.getPrototypeOf(newObj).name;
(which changes the parent object)
You can also shadow it, by setting the value to undefined
(for example):
newObj.name = undefined;
But you can't remove the property on newObj without deleting it from the parent object as the prototype is looked up the prototype chain until it is found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With