如何获得一个未知的JSON层次结构的总深度?(How to get the total depth

2019-08-31 10:33发布

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

Answer 1:

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

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
}

该功能的工作原理如下:

  • 如果对象是不是叶(即对象有孩子属性),那么:
    • 计算每个孩子的深度,保存的最大一个
    • 返回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/



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


文章来源: How to get the total depth of an unknown JSON hierarchy?