Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete Javascript object property?

Tags:

javascript

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
like image 344
fruitjs Avatar asked Apr 15 '16 10:04

fruitjs


People also ask

How do I remove a property from a JavaScript object?

Remove a Property from a JS Object with the Delete Operator delete object. property; delete object['property'];

How do we delete the 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.

How do you remove a property property from an object obj?

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, ...

How do you delete object items?

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.


1 Answers

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.

like image 55
Denys Séguret Avatar answered Oct 12 '22 13:10

Denys Séguret