Fahad Rana
Fahad Rana

Reputation: 70

Delete a object's key also deletes key in the other object - Javascript

I have found myself in a peculiar problem with Javascript. I am trying to maintain a form of state object/ dictionary (dict1) and a final object/ dictionary(dict2) which I have to post.

I assign the object dict1 to my object dict2 when clicking on some buttons. What I want to do is delete the key in dict2 but the behavior is peculiar as it also deletes the key from the dict1. Below is my code:

dict1 = {
    123:{
    456:2
  }
}

dict2 = {}

dict2[123] = dict1[123]


delete dict2[123][456]


console.log(dict1)

// It logs {123 : {} } whereas the dict1 shouldn't change

It seems like the objects are shallow copying somehow.

Upvotes: 2

Views: 53

Answers (1)

AJ_
AJ_

Reputation: 1485

Use the spread operator (...) to create a "duplicate" of the object so that you aren't modifying the original.

Originally, you were copying the reference stored in dict1[123] to dict2[123]. This means that both dict properties point to the same object and that modifications made from one dict can be seen from the other. By using the spread operator, you are adding all the contents of an object to a new one. This means that dict1[123] and dict2[123] will store 2 different references that contain the same data, and you can modify them independently.

Read more about the spread operator here.

dict1 = {
  123:{
    456:2
  }
}

dict2 = {}

dict2[123] = {...dict1[123]}

delete dict2[123][456]

console.log(dict1)
console.log(dict2)

Upvotes: 2

Related Questions