tags:

views:

23

answers:

2

Scenario: - fill object1 - copying the content of object1 to object2 - delete element from object1

Result now: - both object1 and object2 have 1 element deleted...?!

Wished result: - object1 should have 1 element less than object2

The code:

var object1 = new Object();
object1['key_one']   = 'value_1';
object1['key_two']   = 'value_2';
object1['key_three'] = 'value_3';
object1['key_four']  = 'value_4';
var object2 = new Object();
object2 = object1;
delete object1['key_three'];

What am I doing wrong?

A: 

Your code does not do any copying. object2 is simply a new, empty object. Try this:

var object1 = {
  key_one: "value_1",
  key_two: "value_2",
  key_three: "value_3",
  key_four: "value_4"
};
var object2 = {};
for (var prop in object1) {
  object2[prop] = object1[prop];
}
delete object1["key_three"];

Now object2 is a copy of object1, but deleting properties from object1 will not affect object2.

Hope that makes sense.

bcherry
bcherry, you saved my day, it works! thanks a thousand times! stackoverflow rules!
Ozcar
@Ozcar: Mark this answer correct, then. Give the man some rep!
ajm
@Ozcar: don't forget to use `hasOwnProperty`.
Marcel Korpel
yeah, if you have a code base that modifies `Object.prototype`, then `hasOwnProperty` is important.
bcherry
A: 

It doesn't look to me like object2 ever received any of the properties of object1. You're on the right track, but you need to copy them.

var object1 = new Object();
object1['key_one']   = 'value_1';
object1['key_two']   = 'value_2';
object1['key_three'] = 'value_3';
object1['key_four']  = 'value_4';

var object2 = new Object();
for(var i in object1){
    object2[i] =  object1[i];
}
delete object1['key_three'];
Jage