如何获得未知JSON层次结构的总深度? [英] How to get the total depth of an unknown JSON hierarchy?
本文介绍了如何获得未知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
}
该函数的工作原理如下:
The function works as follow:
- 如果对象不是叶子即对象具有children属性),则:
- 计算每个孩子的深度,保存最大值
- return 1 +最深的孩子的深度
jsFiddle: http://jsfiddle.net/chrisJamesC/hFTN8/
jsFiddle: http://jsfiddle.net/chrisJamesC/hFTN8/
EDIT
使用现代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/
jsFiddle: http://jsfiddle.net/chrisJamesC/hFTN8/59/
这篇关于如何获得未知JSON层次结构的总深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文