0

When i create a new object from an existing object, then append a new attribute, why does it update the earlier one?

Is their a solution that does not involve changing my code much?

Here is my example jsfiddle.

var data = [
  {
    "id" : 1,
    "name" : "carrot",
    "price" : 0.10,
    "stock" : 12,
    "bgLocation" : "-1px -54px"
  },
  {
    "id" : 2,
    "name" : "fennel",
    "price" : 1.20,
    "stock" : 6,
    "bgLocation" : "-146px -52px"    
  }
]

var item = data[0];
item.added = 4;

//data[0] should not contain the added attribute.
$('body').append(JSON.stringify(data[0]));
Undefined
  • 11,234
  • 5
  • 37
  • 62

2 Answers2

2

The variables item and data are just references pointing to the same object. By calling.

var item = data[0];

you're not copying the object, you just create a new reference on the object that is addressed with data[0]. Therefore

item.added = 4;

will change the object bot vraiables point to.

Here

How do I correctly clone a JavaScript object?

are some detailed information on how to copy objects in javascript.

Community
  • 1
  • 1
Hans Hohenfeld
  • 1,729
  • 11
  • 14
0

Because all you get is a reference to the original object, not a copy. Thus, if you update this reference, you are implicitly updating the original object.

You can easily create a copy using $.extend():

var item = $.extend({}, data[0]);

DEMO.

João Silva
  • 89,303
  • 29
  • 152
  • 158
  • Thanks for that, this is the simplest solution to my problem. Ill mark as accepted when I can. Cheers :) – Undefined Sep 05 '12 at 14:22