Manipulating Copies of JavaScript Objects with KnockoutJS

I recently ran into an issue when trying to change properties of what I thought was a copy of a JavaScript object.  I made all of the new object’s properties observable, and then tried changing the value of one of the properties in the new object. It turns out that this was also changing the same property in the original object.  This is all because JavaScript objects are assigned by reference, not value! For example:

var x = y;

In the example above, the object x is not a copy of y. It is a reference to y! So how does this relate to knockout?

In my project, we have data from the server given to the client in JSON format.  It is then given to the client-side viewModel, all non-observable.  In order to take the data from the server and make the data we need to be observable, we use a method to set all of an object’s properties to be observable.  This stomps over the original object, which is okay because we don’t ever need the original non-observable object that came from the server.  If, however, I need to clone the object’s data and manipulate properties on the clone, while keeping the original, I’ve found the easiest way is to use the jQuery extend() method.  You can specify whether or not to make a deep (recursive) copy, and even merge 2 objects as well.  The following example makes use of this method:

Notice in the results that the original object has “Not John” as the First name, since it was inadvertently changed on its reference. The object changed using the extend method did not affect the original!

References: w3schools.com

One thought on “Manipulating Copies of JavaScript Objects with KnockoutJS

Leave a Reply

Your email address will not be published. Required fields are marked *