用于遍历和搜索树结构中的节点的助手(D3.js方式)

时间:2015-02-25 11:19:38

标签: javascript d3.js tree helper

当我在d3.js中处理树状结构数据时,我经常需要在数据上调用forEachfilter模拟。 例如,这是数据:

data = {
  id: 0,
  children: [ {
    id: 1,
    children: [ ... ]
  }, {
    id: 2,
    children: [ ... ]
  }]
}

要检查数据中是否存在id = 5的节点,我必须通过所有子节点实现递归搜索功能。像这样:

function hasNodeWithId(node, id) {
    if (node.id === id) {
        return true;
    } else {
        return _.any(node.children || [],
            function(n) { return hasNodeWithId(n, id); });
    }
}

搜索树内的节点是一项常见的任务,所以我想知道d3.js库中是否存在某种辅助函数。如果没有,那么其他人如何处理这类问题呢?

P.S。
有时我可以使用tree.nodes函数来获得平面数组:

var theId = 5,
    tree = d3.layout.tree(),
    nodes = tree.nodes(data), // makes a flat array of all the nodes in the data
    theNode = nodes.filter(function(d) { return d.id === theId; });

但每次我需要遍历数据时调用tree.nodes(data)都是压倒性的,并且在{{1}上有一些副作用(xydepth字段) }}

0 个答案:

没有答案
相关问题