简体   繁体   中英

Deepcopying observable array knockout

I have a observable which is binded to UI, On button click i am creating a new array from observable array and doing manipulation with new array but unfortunately any changes in new array affects old array too.

I am using below code for deep copying.

   var clonedArr = $.extend(true, [], masterArray());

Am i missing something. You can find jsfiddle here ( https://jsfiddle.net/t5a1xfud/ ) for more details

You need to merge the empty array and your original array in a way that $.extend does not modify your original.
Example : https://jsfiddle.net/kyr6w2x3/18/

var newArr = [];
newArr = $.extend( [], self.Array(), newArr );

How to deep copy (or otherwise make sure the arrays aren't linked): https://jsfiddle.net/t5a1xfud/18/

self.newItems(ko.toJS(self.existingItems()));

How to not deep copy (there are other ways too): https://jsfiddle.net/t5a1xfud/19/

self.newItems(self.existingItems());

Note that in the second example after you use the "Copy to new" button, the arrays will be linked. They appear not to be linked, but if you alternate clicking between "Add to existing" and "Add to new" you will see that they do affect eachother. Not the case with the first example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM