Objects in JavaScript are passed by reference. When more than one variable is set to store either an object , array or function , those variables will point to the same allocated space in the memory. Passed by reference.
Similar to adding elements to arrays without mutating them, You can use the spread operator to copy the existing object into a new one, with an additional value. If a value already exists at the specified key, it will be overwritten.
I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).
JSON.parse(JSON.stringify(json_original));
Documentation
Your only option is to somehow clone the object.
See this stackoverflow question on how you can achieve this.
For simple JSON objects, the simplest way would be:
var newObject = JSON.parse(JSON.stringify(oldObject));
if you use jQuery, you can use:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:
In ES6 or TypeScript (2.1+):
var shallowCopy = { ...oldObject };
var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };
Note that if extraProp
is also a property on oldObject, its value will not be used because the extraProp : "abc"
is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With