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!
Nice post. Now that ES6 is pretty popular, with its spread operator, I’d suggest writing a follow-up article comparing making copies via (1) the spread operator, (2) object.assign(), and (3) any other choices. See, for example, http://stackoverflow.com/questions/32925460/spread-operator-vs-object-assign