1

Hello, here is my problem:

When i set an object with another object, like this:

a = {"first":1, "second":2};
b = a;

And then i delete a property from the "a" object, it also deletes the property from the "b" object.

delete a.second;

Heres the jsFiddle

4 Answers4

1

And it will delete it because by doing b = a you do not clone the object a but just copy the reference to it, so practically b is referencing to the same object a.

To clone objects you may use jQuery method $.extend:

var a = { first: 1, second: 2 };
var b = $.extend({}, a);

delete a.second;

console.log(a);  // Object {first: 1}
console.log(b);  // Object {first: 1, second: 2} 
VisioN
  • 143,310
  • 32
  • 282
  • 281
0

Yes, objects in javascript are merely assigned by reference. You have to assign each property manually to the new object or clone it.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

"Setting" an object from another object merely assigns a reference to the same object. No new object is created with the statement

b = a;

After that, variables "a" and "b" both refer to the same single object. Changes made via one or the other of the variables will therefore be made to that same object.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

If the object only contains simple properties (strings, numbers, booleans) you can also use JSON to make a clone of it.

var o = { prop1: true, prop2: "Hello" };

var copy = JSON.parse(JSON.stringify(o));

There is a long discussion about cloning objects here:

What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74