I am trying to copy one observably array to another observable array. I have a form that has a billing address, shipping address and checkbox that when clicked allows the user to copy all of their shipping info to their billing address. The problem I am having is when I copy one observable array to another, then any time I make a change to either observable both observable arrays get updated. I would like to keep both observable array values seperate just copy the values from one to the other.
My observable arrays are set up using the mapping plugin:
self.billingAddress = ko.mapping.fromJS(InitialEmptyAddressModel);
self.shippingAddress = ko.mapping.fromJS(InitialEmptyAddressModel);
Then to copy shipping info to billing after entering shipping information and clicking on 'Use Shipping Address':
self.CopyAddress = function() {
self.billingAddress(self.shippingAddress());
}
I've also tried the following: What is the best way of cloning/copying an observablearray in knockoutJS?
Any help would be appreciated thank you.
You don't really want to copy over the observables that are inside shippingAddress
. You would likely want to get a clean version of it and then apply it to the other mapped object.
Something like:
self.copyAddress = function() {
var clean = ko.mapping.toJS(self.shippingAddress);
ko.mapping.fromJS(clean, self.billingAddress);
};