javascript - How to get the total depth of an unknown JSON hierarchy? -
i've been struggling find/build recursive function parse json file , total depth of children.
the file looks 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 }] }] }] }
you can use recursive function go through 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 follow:
- if object not leaf (i.e object has children attribute), then:
- compute depth of each child, save maximal one
- return 1 + depth of deepest child
- otherwise, return 1
jsfiddle: http://jsfiddle.net/chrisjamesc/hftn8/
edit modern javascript, function this:
const getdepth = ({ children }) => 1 + (children ? math.max(...children.map(getdepth)) : 0)
Comments
Post a Comment