문제

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]));
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top