2

I'm making a script where I create an object, and I want to make a copy of it, but when I assign the object to another variable if I change it will change both.

I've been reading a book and what I understand is that is is a reference and not a value, but I want to copy an object and treat them separately from that point. This is an example of what I do:

var myObject = {};
var copyOfMyObject = myObject;
myObject.foo = 'bar';

console.log(myObject, copyOfMyObject);

//logs Object {foo="bar"} Object {foo="bar"}

Is there a way to copy the whole object where I can change their properties independently without affecting the other?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

1

You will have to map each property to the new array:

Simple one level clone can be made like this:

function clone(a, b) {
    var prop;
    for( prop in b ) {
        b[prop] = a;
    }
}

This will clone all properties from b to a. But keep all other properties in a:

var a = {a: 9, c: 1},
    b = {a: 1, b: 1};

copy(a, b); // {a: 1, b: 1, c: 1}

Deep Clone Object:

The above example will work when dealing with single level objects, but will make a confusion when multiply levels is present, take a look at this example:

var a = {},
    b = { a: { a: 1 } }

clone(a, b);

a.a.a = 2; 
console.log(a); // { a: { a: 2 } }
console.log(b); // { a: { a: 2 } }

The above example proves that the object inside a.a is the same as the one inside b.a.

Community
  • 1
  • 1
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • +1 so after this I can manipulate my objects without affecting the other right –  Jun 02 '13 at 18:25
  • @iker Yes if you are working with single level objects! If you have multi level objects you will have to make a recursive function and maybe you want to take care of arrays, dates, etc aswell. – Andreas Louv Jun 02 '13 at 18:28