myObj = {
prop1: 'alpha',
prop2: 'beta',
priceUpdatedOn: new Date()
};
myObjQuery = myObj;
delete myObjQuery.priceUpdatedOn;
console.log(myObj);
console.log(myObjQuery);
When I do that, the priceUpdatedOn
gets deleted from myObj
as well for some reason. Any idea why?
This is because myObjQuery and myObj are the same object. When you do myObjQuery = myObj
, you aren't making a copy of the object itself, rather a copy of a reference to it. You never directly manipulate objects in JavaScript, instead always through a reference.
EDIT: Cloning objects in JavaScript is not straightforward. Most libraries like jQuery or Ext have a means to do it. To do it manually, something like this works.
var clone = {};
for(var prop in myObj) {
if(myObj.hasOwnProperty(prop)) {
clone[prop] = myObj[prop];
}
}
Keep in mind that is a shallow copy. To do a deep copy, you need to detect if the properties themselves are objects and recursively clone them too. Best to use a library that does all this for you. And also keep in mind this is missing lots of edge cases, and weird things like the object's constructor property. JavaScript is really messy here.
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