Search code examples
javascriptobjectjavascript-objects

How to copy JavaScript object to new variable NOT by reference?


I wrote a quick jsfiddle here, where I pass a small JSON object to a new variable and modify the data from the original variable (not the new variable), but the new variable's data gets updated as well. This must mean that the JSON object was passed by reference, right?

Here is my quick code:

var json_original = {one:'one', two:'two'}

var json_new = json_original;

console.log(json_original); //one, two
console.log(json_new); //one, two

json_original.one = 'two';
json_original.two = 'one';

console.log(json_original); //two, one
console.log(json_new); //two, one

Is there a way to make a deep copy of a JSON object so that modifying the original variable won't modify the new variable?


Solution

  • Important edit: this answer was made in 2014 and there are now better ways of deep-cloning an object.


    I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

    JSON.parse(JSON.stringify(json_original));
    

    Documentation