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

How to get the total depth of an unknown JSON hierarchy?

本文关键字:深度 层次结构 JSON 何获得 未知      更新时间:2023-09-26

我一直在努力寻找/构建一个递归函数来解析这个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
            }]
        }]
    }] 
}

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

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/

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

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));
 }