I am confused. I create a copy from myObjOne, than i delete an entry from myObjOne and JS delete the entry in my copy(myObjTwo) too? But why?
myObjOne = {};
myObjOne['name'] = 'xxx';
myObjOne['id'] = 'yyy';
myObjOne['plz'] = 'zzz';
// clone
myObjTwo = myObjOne;
// remove something
delete myObjOne['name'];
console.dir(myObjTwo);
Update: Removing
Object.createas a method of cloning as indicated in comments.does not clone. It simply copies the reference.
If you want to clone, you can use
JSON.parseandJSON.stringifyWarning: As Raynos mentioned in comments, this JSON based clone does not retain methods of the input object in the output object. This solution is good enough if your object does not contain any methods. Methods are properties of a object that are functions. If
var obj = {add : function(a,b){return a+b;}}thenaddis a method ofobj.If you need a solution that supports copying of methods, then go through these SO answers (as pointed out by musefan, Matt and Ranhiru Cooray)
I would suggest How do I correctly clone a JavaScript object?