3

示例:http: //jsfiddle.net/yeehawjared/bawv0790/

我正在构建一个打开网页的应用程序,加载大型数据树结构的 JSON。TreeModel.js 很好地解析了这个,一切都很好。

随着时间的推移,浏览器会以较小的数据树的形式接收更新。我正试图将我的头结合additionalDatamasterTree. 我想不出一种同时走两个节点并进行逐节点比较的方法。node.model.x如果可以的话,聚合属性并添加子项(如果它们不存在)会很容易。

在下面的代码中,我浏览了附加数据 - 但我不知道如何有效地将新节点组合到masterTree. 有人可以用伪代码帮助我的方法或为我指明正确的方向吗?不断更新我的最佳方式是什么masterTree

非常感谢。

var tree = new TreeModel();
var masterTree = tree.parse(data1);

var additionalData = tree.parse(data2);
additionalData.walk(function (node) {

    // compare additionalData to the masterTree
    if (node.model.id == masterTree.model.id) {
        console.debug('match, combine the attributes')
    } else {
        // add the additional node to the materTree
    }
});
4

1 回答 1

4

看看这个小提琴的例子:http: //jsfiddle.net/bawv0790/1/

重要的功能是mergeNodes。它是一个递归函数,接收 2 个节点,n1 和 n2。首先,它根据 n2 更新 n1 的大小,如果它们丢失,它们会将 n2 个子代添加到 n1,或者如果它们存在则合并它们。

function mergeNodes(n1, n2) {
    var n1HasN2Child, i, n2Child;

    // Update the sizes
    updateSize(n1, n2);

    // Check which n2 children are present in n1
    n1HasN2Child = n2.children.map(hasChild(n1));

    // Iterate over n2 children
    for (i = 0; i < n1HasN2Child.length; i++) {
        n2Child = n2.children[i];
        if (n1HasN2Child[i]) {
            // n1 already has this n2 child, so lets merge them
            n1Child = n1.first({strategy: 'breadth'}, idEq(n2Child));
            mergeNodes(n1Child, n2Child);
        } else {
            // n1 does not have this n2 child, so add it
            n1.addChild(n2Child);
        }
    }
}

如果对孩子进行排序,检查哪些 n2 个孩子在 n1 中可能会大大改善。

于 2014-10-11T08:22:52.317 回答