Frage

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]));
War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top