如何获取未知 JSON 层次结构的总深度? [英] How to get the total depth of an unknown JSON hierarchy?

查看:17
本文介绍了如何获取未知 JSON 层次结构的总深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

文件看起来像这样:

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

推荐答案

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

You can use a recursive function to go through the whole tree:

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 + 最深孩子的深度

    jsFiddle:http://jsfiddle.net/chrisJamesC/hFTN8/

    编辑使用现代 JavaScript,该函数可能如下所示:

    EDIT With modern JavaScript, the function could look like this:

    const getDepth = ({ children }) => 1 +
        (children ? Math.max(...children.map(getDepth)) : 0)
    

    jsFiddle:http://jsfiddle.net/chrisJamesC/hFTN8/59/

    这篇关于如何获取未知 JSON 层次结构的总深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆