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?

2
  • 2
    That's not a "JSON literal". It's an "object literal". It has nothing to do whatsoever with JSON.
    – gen_Eric
    Mar 21, 2013 at 17:41
  • 1
    This is not JSON. This is a javascript object using the object literal syntax. Mar 21, 2013 at 17:41

1 Answer 1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.