3

A simple example of what I'd like to do:

data = {name: 'fred'};

newData = {};
newData.name = data.name;

newData.name = 'ted';

console.log(data.name); // I want this to be ted not fred

Is it possible in Javascript to edit the second object and have it modify the first? I'm using alloyui 1.5 (yui 3.4.0) and trying to merge objects to create a datatable so the data appears on a single row but it needs to be editable, so it needs to point back to the original object.

Is such a thing possible or will I need to use events to push the data back to the first object?

Sam Meek
  • 43
  • 1
  • 6

2 Answers2

1

You can do this if property of your objects is also an object. This works:

data = {name: {first:'fred'}};

newData = {};
newData.name = data.name;

newData.name.first = 'ted';

console.log(data.name.first) // outputs ted
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
-1

yes, you can make a new object reference of the first( your data object) as newData using javascripts Object(). Changing either objects property reflects to the other.

data = {name: 'fred'};

var newData = new Object(data);

newData.name = 'ted';

console.log(data.name);// outputs ted

you can read more about Object() here

Tyro Hunter
  • 755
  • 1
  • 8
  • 20
  • `new Object(data)` does not create a new object reference. you should note that `newData === data` in this example. – zzzzBov Sep 19 '13 at 02:02
  • You don't need to that javascript passes objects by reference as default so ```data = {name: 'ted'}; newData = data; newData.name = 'fred';``` would achieve the exact same thing. I think what OP want is to copy various properties of ```data``` to ```newData``` without beeing both the same object. So he is still able to add properties to ```newData``` that should not be on ```data```. And thats not a big problem as long as the value is not an immutable object like a string. – Manuel Görlich Sep 19 '13 at 02:02
  • As Manuel Görlich mentions, I'm trying to use various properties without it being the same object. I wasn't aware that strings were immutable so thanks Manuel. – Sam Meek Sep 19 '13 at 02:24