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";
2
  • JSON has nothing to do with what you're attempting. Those are just object literals. Commented Jan 17, 2015 at 21:28
  • possible duplicate of What is the most efficient way to clone an object? Commented Jan 17, 2015 at 21:29

2 Answers 2

3

You can use this:

var copyArray = JSON.parse(JSON.stringify(someArray));
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is identical to chiliNUT. I wish I could mark both of you as answers. +1 for your help. Thank you.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.