您可以使用递归函数遍历整个树:
getDepth = function (obj) { var depth = 0; if (obj.children) { obj.children.forEach(function (d) { var tmpDepth = getDepth(d) if (tmpDepth > depth) { depth = tmpDepth } }) } return 1 + depth}该函数的工作原理如下:
- 如果对象不是叶子(即对象具有children属性),则:
- 计算每个孩子的深度,保存最大的一个
- 返回1 +最深的孩子的深度
- 否则,返回1
jsFiddle:http :
//jsfiddle.net/chrisJamesC/hFTN8/
编辑 使用现代Javascript,该函数可能如下所示:
const getDepth = ({ children }) => 1 + (children ? Math.max(...children.map(getDepth)) : 0)jsFiddle:http :
//jsfiddle.net/chrisJamesC/hFTN8/59/



