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/
That is because the object is not copied. The
obj.keyproperty will only contain a reference to the object, so when you assign something toobj.key.testthe effect is the same as assigning it tojsonobj.test.You can use the jQuery method extend to create a copy:
This will copy the values into the newly created object (
{}).