I have the following code (I am using the jQquery libary):
var obj = {};
var objstring = '{"one":"one","two":"two","three":"three"}'
// first console output
console.log(objstring);
var jsonobj = $.parseJSON(objstring);
// second console output
console.log(jsonobj);
obj.key = jsonobj;
obj.key.test = "why does this affect jsonobj? (even in the second console output)";
// third console output
console.log(jsonobj);
My Question: When I do obj.key = jsonobj and I change values in the new obj.key. Why do values in jsonobj then also change? And how would I avoid that? (I want a new "copy" of jsonobj).
I made this test case: http://jsfiddle.net/WSgVz/
I want to address a small piece of what is going on here, since others have done so well addressing the larger issues of JavaScript object references:
// second console output
console.log(jsonobj);
obj.key = jsonobj;
obj.key.test = "why does this affect jsonobj? (even in the second console output)";
This is the result of a documented WebKit bug, that console.log
statements do not output the object at the time of calling console.log
, but instead some time later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With