Search code examples
javascriptjquerydelete-operator

jQuery 'delete' operator also deletes previous setted object


Hello, here is my problem:

When i set an object with another object, like this:

a = {"first":1, "second":2};
b = a;

And then i delete a property from the "a" object, it also deletes the property from the "b" object.

delete a.second;

Heres the jsFiddle


Solution

  • And it will delete it because by doing b = a you do not clone the object a but just copy the reference to it, so practically b is referencing to the same object a.

    To clone objects you may use jQuery method $.extend:

    var a = { first: 1, second: 2 };
    var b = $.extend({}, a);
    
    delete a.second;
    
    console.log(a);  // Object {first: 1}
    console.log(b);  // Object {first: 1, second: 2}