Search code examples
javascriptobjectscoping

When creating a new object why does it update the old one?


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]));

Solution

  • 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.