0

I have been trying to figure out how to make a copy of a JSON object array that can be modified without changing the original. I do see a lot of discussion regarding objects being passed as a reference by default, but I don't understand how to avoid this default behavior.

The example jQuery below is not real code, but I think it illustrates what I am trying to accomplish. Can anyone help me understand how to code the following example so that _copy can be modified with _master being left unmodified?

// Master - should never get modified
_master = [ 
    Object { id=0, name="Charlie", city="Memphis", state="TN" },
    Object { id=1, name="Steve", city="Chicago", state="IL" } 
];

// Copy of Master that can be modified
_copy = _master;

// Modify _copy only - leave _master unmodified
_copy[0].name = "Charles";
rwkiii
  • 5,716
  • 18
  • 65
  • 114
  • JSON has nothing to do with what you're attempting. Those are just object literals. – Brad Jan 17 '15 at 21:28
  • possible duplicate of [What is the most efficient way to clone an object?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) – Brad Jan 17 '15 at 21:29

2 Answers2

3

You can use this:

var copyArray = JSON.parse(JSON.stringify(someArray));
David Xu
  • 5,555
  • 3
  • 28
  • 50
  • Your answer is identical to chiliNUT. I wish I could mark both of you as answers. +1 for your help. Thank you. – rwkiii Jan 17 '15 at 22:03
2

_copy=JSON.parse (JSON.stringify (_master));

is a quick way to do it. The encode converts _master to a string representation of the variable, and the parse consumes it and turns it back into an array.

Any referential/memory connection is severed once the variable is converted to a string.

chiliNUT
  • 18,989
  • 14
  • 66
  • 106