-1

Have I gone mad?

I am trying to clone an object an then delete an element from it, but it also deletes from the initial object. I feel like I no longer understand life!

var obj1 = { 
  'name' : 'bob',
  'hair' : 'brown'
}

var obj2 = obj1;
delete obj2.hair;

This delete's obj1.hair. How? What? Why?

user3822370
  • 641
  • 7
  • 20

3 Answers3

0

var obj2 = obj1; does not clone the object. It merely makes a second variable pointing at the exact same object. In Javascript, objects are assigned by reference (not by copy). So, both variables point to the one and only object.

If you truly want a clone, then you have to actually make a clone. This is not a feature built into the Javascript language, but you can construct a clone function. There are many out there.

Some references:

What is the most efficient way to deep clone an object in JavaScript?

How do I correctly clone a JavaScript object?

What is the most efficient way to deep clone an object in JavaScript?

How to Deep clone in javascript

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

obj2 and obj1 refer to the same object. You'll need to clone it or new up two different references of an object with similar values.

function Obj(name, hairColor){
    this.name = name;
    this.hair = hairColor;
};

var obj1 = new Obj('bob', 'brown');
var obj2 = new Obj('bob', 'brown');

delete obj2.hair;

Another alternative, if defining an Obj function as depicted above, is not feasible, is to write a function that loops over the properties of an object and returns a new object with the same values.

Community
  • 1
  • 1
Alex
  • 34,899
  • 5
  • 77
  • 90
0
function clone(obj) {
    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = obj.constructor(); // changed

    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            temp[key] = clone(obj[key]);
        }
    }
    return temp;
}

usage

var obj1 = { 
  'name' : 'bob',
  'hair' : 'brown'
}

var obj2 = clone(obj1);

All credit goes here https://stackoverflow.com/a/122190/1564365

(I feel so stupid answering this question.)

Community
  • 1
  • 1
Kyslik
  • 8,217
  • 5
  • 54
  • 87