如何走在d3.js树

问题描述:

我使用d3.nest创建从下列格式的JSON分层数据:如何走在d3.js树

[ 
{ 
    'account_name':'abc123', 
    'fiscal_quarter':'q1', 
    'fiscal_period':'q1p1', 
    'fiscal_week_period':'q1p1w1', 
    'total':50.0 
}, 
...... 
] 

,我需要做的是建立在每个具有汇总嵌套数据水平如

{ 
    key:'account_name', 
    total:sum of all values in tree, 
    values:array of children 
} 

是否有可能与价值观的非叶节点,而不是仅仅子节点,或等效的情况下,在每个节点走嵌套的数据集,并计算值?

你是对的,D3的nest.rollup只处理叶组。所以你需要编写一个递归函数来遍历嵌套的入口树并计算agregates。这里的例子总和为:

var topChildren = d3.nest() 
 
    .key(function(item) 
 
    { 
 
    return item['fiscal_quarter']; 
 
    }) 
 
    .key(function(item) 
 
    { 
 
    return item['fiscal_period']; 
 
    }) 
 
    .entries(data); 
 
var root = {'values': topChildren, 'key': null}; 
 

 
function rollup(node) 
 
{ 
 
    node['sum'] = node['values'].reduce(function(result, item) 
 
    { 
 
    return result + (item['values'] ? rollup(item) : item['total']); 
 
    }, 0); 
 
    return node['sum']; 
 
} 
 
rollup(root); 
 
console.log(root);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 
<script> 
 
var data = [ 
 
{ 
 
    'account_name':'abc123', 
 
    'fiscal_quarter':'q1', 
 
    'fiscal_period':'q1p1', 
 
    'fiscal_week_period':'q1p1w1', 
 
    'total':50.0 
 
}, 
 
{ 
 
    'account_name':'abc234', 
 
    'fiscal_quarter':'q2', 
 
    'fiscal_period':'q2p3', 
 
    'fiscal_week_period':'q2p3w1', 
 
    'total':60.0 
 
}, 
 
{ 
 
    'account_name':'abc345', 
 
    'fiscal_quarter':'q2', 
 
    'fiscal_period':'q2p4', 
 
    'fiscal_week_period':'q1p4w1', 
 
    'total':70.0 
 
}, 
 
{ 
 
    'account_name':'abc456', 
 
    'fiscal_quarter':'q3', 
 
    'fiscal_period':'q3p1', 
 
    'fiscal_week_period':'q3p1w1', 
 
    'total':80.0 
 
}, 
 
{ 
 
    'account_name':'abc456', 
 
    'fiscal_quarter':'q3', 
 
    'fiscal_period':'q3p2', 
 
    'fiscal_week_period':'q3p2w1', 
 
    'total':90.0 
 
} 
 
]; 
 
</script>

旁注。 +运算符优先于三元运算符,因此您需要括号来更改优先级。它的工作原理没有错误,但结果不正确。如果您想挑战自己去理解JavaScript的设计缺陷之一(弱类型,不应该将其与动态类型混淆),请删除括号并尝试理解为什么它以这种方式工作。我刚刚完成,忘记了运营商优先级: -/

+0

谢谢!这节省了我很多时间通过文档挖掘。 – sakurashinken 2014-12-11 19:04:37