1

I have a JSON literal as follows:

var json_1 = {
    "name": "Tim",
    "toys": ["ball", "bat", "lego"]
};

Now I clone this as follows:

var json_2 = json_1;

If I remove a toy from json_1 (using splice())the same seems to be getting removed from json_2. How do I create a copy without them being dependent on each other?

callmekatootie
  • 10,989
  • 15
  • 69
  • 104

1 Answers1

5

When you do:

var json_2 = json_1

you're actually not "cloning" the object you're merely aliasing it. So all operation on json_1 will be mirrored on json_2 and vice versa. To really clone your object take a look at: https://stackoverflow.com/a/728694/2003420

Community
  • 1
  • 1
El Bert
  • 2,958
  • 1
  • 28
  • 36