javascriptjquerytreemodel

Cloning a JS TreeModel tree


I need to clone a tree I made using TreeModel.js. What I exactly need to do is duplicating it, make changes to it and check if the number of nodes decreased. If it did, revert to the original tree. Here's a small example of what I do so far to duplicate it, which is not correct:

var tree = new TreeModel();
var root = tree.parse({
    id: 0,
    name: "Root",
    children: [{id: 1, name: "1", children: []},{id: 2, name: "2", children: []}]
});

console.log(root)
var dup = tree.parse(root)
console.log(dup)

Here's a Fiddle. You'll see the difference between the trees by looking at the console:

Node {config: Object, model: Object, children: Array[2], isRoot: function, hasChildren: function…}
Node {config: Object, model: Node, children: Array[2], isRoot: function, hasChildren: function…}

Is there any way to properly clone such a structure? I looked for cloning JS object but still, I can't find a way for cloning this object exactly (such as the prototypes of properties like the model...)


Solution

  • You can deep clone the model of the first tree and parse it again to get a second tree.

    Taking on your example:

    function deepCopy(obj) {
        // You can also use the jquery extend method here
        return JSON.parse(JSON.stringify(obj));
    }
    
    var dup = tree.parse(deepCopy(root.model));
    

    Important: If you do not deep clone the model, and just parse it again, you'll end up with the same underlying model shared by both trees which will certainly cause inconsistencies.