Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior when deleting object property after copying object

Tags:

javascript

  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?

like image 302
Shamoon Avatar asked Jan 17 '23 22:01

Shamoon


1 Answers

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.

like image 141
Matt Greer Avatar answered Jan 31 '23 09:01

Matt Greer