When creating a new object why does it update the old one?
-
30-06-2021 - |
Domanda
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?
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]));
Soluzione
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.
Altri suggerimenti
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.