8

I've been struggling to find/build a recursive function to parse this JSON file and get the total depth of its children.

The file looks something like this:

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
            }]
        }]
    }] 
}
4

2 回答 2

31

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

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/

于 2013-04-18T06:29:28.413 回答
3

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

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));
 }
于 2013-04-18T06:33:41.647 回答