Cloning a JS TreeModel tree

女生的网名这么多〃 提交于 2019-12-05 06:11:07

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.

I finally came to a solution that may help anyone with the same problem:

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.model)
console.log(dup)

The parse function takes a model as parameter and the model of root seems to work fine.

EDIT: this solution may bring inconsistencies since the 2 trees are based on the same model. JNS's solution is more appropriate.

Why not trying a jQuery deep copy?

var dup = jQuery.extend(true, {}, tree)

I tried your fiddle but it doesn't seem to work.

https://github.com/mrluc/owl-deepcopy this worked for me.

newTree = deepCopy(tree)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!