2017-02-23 18 views
0

ノードの子孫のカウントを取得する方法を知りたいのですが。D3.jsツリーレイアウト - 子孫の数を取得したい

私はこのコードを使用して子供の数を得ることができます。

console.log(d.children.length); 

しかし、そのノードの子孫のカウントはどのように取得できますか?

再発を使用する必要がありますか?

助けていただければ幸いです。

答えて

1

これは再帰によるものです。

function getCount(parent) { 
 
    var count = 0; 
 

 
    if (Array.isArray(parent.children)) { 
 
    count += parent.children.length; 
 
    parent.children.forEach(function(child) { 
 
     if (Array.isArray(child.children)) { 
 
     count += getCount(child); 
 
     } 
 
    }); 
 
    } 
 

 
    return count; 
 
} 
 

 
var d = { 
 
    children: [ 
 
    1, 
 
    { 
 
     children: [ 
 
     1, 
 
     2 
 
     ] 
 
    }, 
 
    2, 
 
    3 
 
    ] 
 
}; 
 

 
console.log(getCount(d));

+0

おかげではなく、正しく動作していない何 – Guru

+0

を動作していませんか?どうやって使ってるの? –

+0

子供がいる場合、あなたの親は計算していません。 (C、D、E) – Guru

関連する問題