user2995387
user2995387

Reputation: 21

how to create deep copy of knockout observable array / object

function getModified(lineData) {

  var newObject = $.extend(true, {}, lineData);               
  newObject.Lines('test')

};

I have extend the observable array to new variable newObject . But if I change anything in newObject, Changes are also reflected to LineData .

In short how to create deep copy of lineData observable array which will not updated lineData. If I modify newObject.

Upvotes: 2

Views: 1683

Answers (1)

Teddy
Teddy

Reputation: 797

ko.utils.clone = function (obj) {
    var target = new obj.constructor();
    for (var prop in obj) {
        var propVal = obj[prop];
        if (ko.isObservable(propVal)) {
            var val = propVal();
            if ($.type(val) == 'object') {
                target[prop] = ko.utils.clone(val);
                continue;
            }
            target[prop](val);
        }
    }
    return target;
};

Here is my solution, Hope it helps.

// obj is your viewModel object.

Upvotes: 2

Related Questions