0

This is kinda silly question, but I have noticed that when I, let's say declare one object

const test = {"foo": 1, "bar": 2}
console.log(test)

And then declare new variable, and give it value of the first object

const test2 = test;

Deleting key from the second variable, it deletes from both.

delete test2.foo
console.log(test2)
console.log(test)

Can someone explain why is this a thing, and how to avoid this problem?

(https://jsfiddle.net/eLxkbx15/1/)

noitse
  • 1,045
  • 9
  • 27
  • In the jsfiddle you are trying to delete a property `user` which does not exist on either of your objects – Michael Hancock Sep 29 '17 at 08:06
  • The relevant answer in the duplicate is probably [this one](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object#answer-30042948), unless nested cloning is required – CodingIntrigue Sep 29 '17 at 08:19

2 Answers2

1

When doing const test2 = test; you are not creating a new object, but just copying a reference to the same object. If you want to create a brand new object, you should do a shallow clone:

const test2 = Object.assign({}, test);

Then you can delete:

delete test2.user;
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
0

The problem is that you are assigning the reference and not copying the object to the new variable. So when you delete the property then it is deleting from both.

You can use Object.assign() Or you can use third party library like lodash's _.clone()

eesdil
  • 1,931
  • 3
  • 16
  • 25