0

I am trying to remove a property from an Person object like this:

const Person = {
  firstname: 'John',
  lastname: 'Doe'
}

console.log(Person.firstname);
// Output: "John"

delete Person.firstname;

console.log(Person.firstname);
// Output: undefined

When I am using this delete operator is working fine and Person.firstname log is showing as undefined as expected. But when I create a new object using this Person object using Object.create() method like this:

const Person = {
  firstname: 'John',
  lastname: 'Doe'
}

const Person2 = Object.create(Person);

console.log(Person2.firstname);
// Output: "John"

delete Person2.firstname;

console.log(Person2.firstname);
// expected output: undefined
// actual output: "John"

You can see Person2.firstname is returning "John" in the end, when I was expecting it to work same way as done in the first snippet and return undefined.

So, my questions here are:

  • Why is delete Person2.firstname not working?
  • Also, how can we delete firstname property from the Person2 object?

Thanks for your help.

Zuckerberg
  • 1,781
  • 2
  • 10
  • 19

2 Answers2

2

delete will only successfully remove a property from an object if the property to be deleted is an own non-configurable property. Here, your Person2 does not have an own property of firstname, so delete Person2.firstname doesn't work. The property exists on the internal prototype of Person2, but not on Person2 itself.

To delete the property, you'll have to call delete with the prototype object:

delete Person.firstname;

const Person = {
  firstname: 'John',
  lastname: 'Doe'
}
const Person2 = Object.create(Person);
delete Person.firstname;
console.log(Person2);

or, if you don't already have a reference to it, use Object.getPrototypeOf:

delete Object.getPrototypeOf(Person2).firstname;

const Person = {
  firstname: 'John',
  lastname: 'Doe'
}

const Person2 = Object.create(Person);
delete Object.getPrototypeOf(Person2).firstname;
console.log(Person2);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

you are creating a shallow copy and you want to do deep copy

tht can be achieved by something like

const Person = {
  firstname: 'John',
  lastname: 'Doe'
}



const Person2 = Object.assign({},Person);

console.log(Person2.firstname);
// Output: "John"

delete Person2.firstname;

console.log(Person2.firstname);
// expected output: undefined
// actual output: "undefined"
console.log(Person2.lastname)

this will give you more clarity on shallow and deep copy