Skip to content Skip to sidebar Skip to footer

Assigning A Var To Temp Var Doesn't Stop Origianal Var From Changing

Alright stackoverflow, I've been working hours on solving an issue in javascript (writing in NodeJS server) but I really don't get it. This is what happens: var data = {x: 50}; var

Solution 1:

You'll have to clone the original object. This is because storing the object in another variable doesn't create a new object with the same properties as the previous one; it just creates a reference to the same object. Sadly, there aren't any built in solutions to get around this, but there are a few solutions. Here some that come to mind:

var temp = JSON.parse(JSON.stringify(data)); // clones the object using a hack

Or:

var temp = {}; // creates a new object and gives it all the same properties as// the old one.for(prop indata) {
    if(data.hasOwnProperty(prop)) {
        temp[prop] = data[prop];
    }
}

Not to be self-promoting, but I've written up a blog post about this subject which goes into a little more detail. You can find here.

Solution 2:

Assigning an object to a variable does not make a copy of the object. It just creates another reference to the same object. Both variables will then point to the exact same object and changing properties of either one (data and temp in your example) will change the exact same object.

To make a copy of an object, one has to actually make an explicit copy of the object by copying all the properties to a new object.

Solution 3:

You can use the clone method of the underscore library to easily clone an object.

var temp = _.clone(data);

Post a Comment for "Assigning A Var To Temp Var Doesn't Stop Origianal Var From Changing"