Tuesday 21 November 2017

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





I wrote a quick jsfiddle rel="noreferrer">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?


itemprop="text">
class="normal">Answer



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





No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...