0

I co ordinates stored as an object and have duplicated the data so i have a copy before the co ordinates change. But the problem is, when I change the co ordinates both copies change to the new version and I lose the original.

So i create it like this:

myObj          = {};
myObj.position = {'x':12,'y':24};
myObj.startPos = myObj.position;

So if i change myObj.position, I don't want myObj.startPos to change. What is the simplest way to prevent this from occurring?

Sir
  • 8,135
  • 17
  • 83
  • 146
  • also you can `JSON.parse(JSON.stringify(obj))` – MightyPork Jan 09 '15 at 20:30
  • The question itself is asked a little differently than the duplicate, but the answers will surely just be duplicates of that question, so better to just close and reference the canonical question on the subject of cloning objects. – adeneo Jan 09 '15 at 20:37
  • For your specific use-case (you shouldn't have ran into this problem) why not: `function MyObj(x,y){ this.position={'x':x, 'y':y}; this.startPos={'x':x, 'y':y}; } myObj=new MyObj(12, 24);` ? Alternatively replace `myObj.startPos = myObj.position;` with `myObj.startPos = {'x':myObj.position.x, 'y':myObj.position.y};` Both of which are going to be a lot faster than trying to clone the object (as explained in other answers). – GitaarLAB Jan 09 '15 at 20:56

1 Answers1

1

The problem is that assigning object doesn't make a copy of it. Instead it is something called a reference for which reason when you change other, the other changes too. You should see this answer about how to most efficiently copy an object in JavaScript.

If you are using any library such as jQuery you can do

myObj.startPos = jQuery.extend({}, myObj.position);

Underscore.js

myObj.startPos = _.clone(myObj.position);

Prototype.js

myObj.startPos = Object.clone(myObj.position);

Plain JavaScript function to achieve the same thing

function clone(obj) {
    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = obj.constructor(); // changed

    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            temp[key] = clone(obj[key]);
        }
    }
    return temp;
}

and then use

myObj.startPos = clone(myObj.position);
Community
  • 1
  • 1
Roope Hakulinen
  • 7,326
  • 4
  • 43
  • 66
  • Is there a simple way to assign the data rather than a reference? Assume that position isn't hard coded so i couldn't just type it in. – Sir Jan 09 '15 at 20:29
  • Updated the answer to contain link into that question with tens of answers describing different ways. – Roope Hakulinen Jan 09 '15 at 20:30