Skip to content Skip to sidebar Skip to footer

Why Does Updating Properties In One Object Change Another Object?

I'm loading JSON data into an object via ajax, copying that object to new objects (initData and newData). When I change the property of newData, the property of initData also chang

Solution 1:

It looks like data[prop] is an object (since you are later referring to newData.properties.Protein). Objects are always passed by reference, with the variable just being a pointer to it.

Since you're getting JSON in the first place, your object is JSON-able, so you can use that to "clone" the object:

$.getJSON(...,function(data) {
    initData = JSON.parse(JSON.stringify(data));
    newData = JSON.parse(JSON.stringify(data));
});

This will ensure that the objects are separate. There are other ways to do this, but this one avoids the manual recursion by using built-in methods (always faster)

Solution 2:

This sets both to reference the same memory space:

initData[prop] = data[prop];
newData[prop] = data[prop];

...so when you change newData, you also change initData. Instead of assigning by reference, you'll want to create a copy. I have to run, so I can't provide an example of that right now.

Post a Comment for "Why Does Updating Properties In One Object Change Another Object?"