1

I have two objects, obj1 and obj2. I want one to have the same properties and values as the other when the user clicks a button, so I write this line:

main.obj1.data=$.extend({},main.someArray[0].data); 

But now updating main.obj1.data automatically updates main.someArray[0].data and vice versa. I tested it by checking that this is true with console.logs immediately after that line of code. I thought that this command would clone the objects but not make them aliases of the same object. What am I doing wrong?

I have messy code to sort through before this command...is there anything I might have put in my code before that point which would cause $.extend to no longer work like I think it should?

3
  • doesn't direct assignment work for this? like obj1 = obj2 Commented Dec 23, 2013 at 20:35
  • 1
    use $.extend(true, {}, obj) Commented Dec 23, 2013 at 20:35
  • @Huangism the problem could not be solved by direct assignment, because of object reference. Commented Dec 23, 2013 at 22:17

2 Answers 2

1

There is two way to solve this

1. main.obj1.data={}; $.extend(main.obj1.data,main.someArray[0].data); 2. main.obj1.data=$.extend(true,{},main.someArray[0].data) 

Actually both is doing the same thing You can read more about $.extend()

Sign up to request clarification or add additional context in comments.

Comments

0

jQuery extend copy the values so the copied object shouldn't be linked to the initial object. You can verify that in this jsfiddle: http://jsfiddle.net/cFtA7/ (open your console and run the script).

The first parameter in $.extend(true,{},main.someArray[0].data) serve to deep copy your object. If your object has many levels, use this parameter, otherwise, it's not needed.

I'm guessing, but is that possible that your extend code is on a bind object that is called every time you update either one of the values?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.