如何获得未知JSON层次结构的总深度?

时间:2013-04-18 06:08:29

标签: javascript json d3.js nested

我一直在努力寻找/构建一个递归函数来解析这个JSON文件并获得其子级的总深度。

该文件看起来像这样:

var input = {
    "name": "positive",
    "children": [{
        "name": "product service",
        "children": [{
            "name": "price",
            "children": [{
                "name": "cost",
                "size": 8
            }]
        }, {
            "name": "quality",
            "children": [{
                "name": "messaging",
                "size": 4
            }]
        }]
    }, {
        "name": "customer service",
        "children": [{
            "name": "Personnel",
            "children": [{
                "name": "CEO",
                "size": 7
            }]
        }]
    }, {
        "name": "product",
        "children": [{
            "name": "Apple",
            "children": [{
                "name": "iPhone 4",
                "size": 10
            }]
        }]
    }] 
}

2 个答案:

答案 0 :(得分:26)

您可以使用递归函数遍历整个树:

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/

答案 1 :(得分:2)

这将计算树中“叶子”的数量:

var treeCount = function (branch) {
    if (!branch.children) {
        return 1;
    }
    return branch.children.reduce(function (c, b) {
        return c + treeCount(b);
    }, 0)
}

另一种获得深度的方法:

var depthCount = function (branch) {
    if (!branch.children) {
        return 1;
    }
    return 1 + d3.max(branch.children.map(depthCount));
 }