Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
            }]
        }]
    }] 
}
like image 292
jfk83 Avatar asked Apr 18 '13 06:04

jfk83


2 Answers

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
}

The function works as follow:

  • If the object is not a leaf (i.e the object has the children attribute), then:
    • Compute the depth of each child, save the maximal one
    • return 1 + the depth of the deepest child
  • Otherwise, return 1

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

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/

like image 83
Christopher Chiche Avatar answered Sep 22 '22 05:09

Christopher Chiche


This will count the number of "leaves" in a tree:

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

And an alternative way to get depth:

var depthCount = function (branch) {
    if (!branch.children) {
        return 1;
    }
    return 1 + d3.max(branch.children.map(depthCount));
 }
like image 36
minikomi Avatar answered Sep 23 '22 05:09

minikomi