Predrag Davidovic
Predrag Davidovic

Reputation: 1566

Delete property from shallow copied object

If I have one object, and shallow copy of it. For example:

var person = {
  name: "Foo",
  age: 10,
  child: {
    name: "Matrix"
  }
}

var copiedPerson = {...person}
console.log(person, copiedPerson);

If I change person.name = "NewName";, copedPerson will stay intact.

If I change person.age = 8;, copiedPerson will stay intact.

But if I change person.child.name = "Neo";, copiedPerson.name will also through reference to point also to same name "Neo".

Everything about that is clear to me.

But I do not understand, why when I delete person.child;, nothing happens to copiedPerson.child;

In my logic cause both of them changes when I change one of them, now I also expected when one of them is deleted that other one should also be deleted. (Cause they references to same location in memory)

Can someone explain me why this didn't happen and which part I misunderstood?

Upvotes: 3

Views: 1129

Answers (3)

Fakt309
Fakt309

Reputation: 861

it is cause the different variables specify on the same object. You should clone obj by cloneObj function

function cloneObj(obj) {
  var res = {};
  for (var i in obj) {
    if (typeof obj[i] == "object") {
      res[i] = cloneObj(obj[i]);
    } else {
      res[i] = obj[i];
    }
  }
  
  return res;
}

var person = {
  name: "Foo",
  age: 10,
  child: {
    name: "Matrix"
  }
}

var copiedPerson = cloneObj(person);

copiedPerson.child.name = "Neo";

console.log(person);
console.log(copiedPerson);

Upvotes: -1

d_bhatnagar
d_bhatnagar

Reputation: 1497

There is a little gap in the mental model you're having about the references right now. So essentially, you understand that if you change the nested object person.child.name the value in the copiedPerson.child.name would change too.

But at the end of the day, the child property is only containing the reference of the nested object for both person and the copiedPerson objects.

So, when you delete it from the original person object, you're deleting the reference of this nested object from the person's child property but this nested object still remains in the memory

Hence, the reference contained in the copiedPerson.child still remains untouched and can access this object saved in the memory

Upvotes: 1

Bergi
Bergi

Reputation: 665020

delete does not destroy the object that is referenced by a variable or property.

delete removes a property from an object - in your case the person object - just like an assignment adds it.

Upvotes: 0

Related Questions