fruitjs
fruitjs

Reputation: 765

How to delete Javascript object property?

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

Upvotes: 13

Views: 11279

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382102

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.

Upvotes: 16

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67197

Basically Object.create will create an object , set its prototype as per the passed object and it will return it. So if you want to delete any property from the returned object of Object.create, you have to access its prototype.

var obj = { name:"Tom" };
var newObj = Object.create(obj);
delete Object.getPrototypeOf(newObj).name
console.log(newObj.name); //undefined.

Upvotes: 4

Related Questions