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?

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

But what if i told you 'fred' is an object :P
@ManuelGörlich doesn't matter, name.first will reference a new object then: jsfiddle.net/6H8VG
-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

3 Comments

new Object(data) does not create a new object reference. you should note that newData === data in this example.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.