Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a one javascript object with another object

On page load I am creating two Javascript Objects, objDemo1 and objDemo1Backup where the latter is simply an exact copy of the first.

e.g.

objDemo1 { 
    sub_1 = { something: 123, somethingElse: 321 },
    sub_2 = { something: 456, somethingElse: 654 }
}

I can modify the values in sub_ as well as add / delete new sub_'s but the only object I am editing is objDemo1. i.e. I never change objDemo1Backup

I have a reset button that when clicked will reset objDemo1 back to what it was when the page originally loaded (i.e. objDemo1 = objDemo1Backup). This is where I am having the issue..

How do I set objDemo1 to objDemo1Backup?

I have tried:

objDemo1 = objDemo1Backup;

and

objDemo1 = null;
var objDemo1 = objDemo1Backup;

...as well as similar variations but nothing seems to work. Any ideas?

  • Note: I can confirm that at the point of resetting, objDemo1Backup is exactly the same as it was when I created it and objDemo1 has changed.
  • My code is definetly hitting the "reset" functionality, where I've tried the objDemo1 = objDemo1Backup... I just cannot figure out the syntax to replace the object.
like image 556
Adam Tomat Avatar asked Dec 18 '12 16:12

Adam Tomat


People also ask

How do you change an object in JavaScript?

To change the value of an existing property of an object, specify the object name followed by: a dot, the name of the property you wish to change, an equals sign, and the new value you wish to assign.

Can we have two properties with the same name inside an object?

You cannot. Property keys are unique.


1 Answers

I'm using angularjs and it took me some time to find out how to copy an object to another object. Normally you'll get an objects clone by calling clone or here in angular copy:

var targetObj = angular.copy(sourceObj);

This gives you a new cloned instance (with a new reference) of the source object. But a quick look into the docs reveals the second parameter of copy:

angular.copy(sourceObj, targetObj)

This way you can override a target object with the fields and methods of the source and also keep the target objects reference.

like image 149
schmijos Avatar answered Oct 10 '22 10:10

schmijos