2014-12-10 69 views
1

我使用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 
} 

是否有可能與價值觀的非葉節點,而不是僅僅子節點,或等效的情況下,在每個節點走嵌套的數據集,並計算值?

回答

2

你是對的,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