我一直在努力寻找/构建一个递归函数来解析这个 JSON 文件并获取其子文件的总深度。
该文件看起来像这样:
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
}]
}]
}]
}
您可以使用递归函数来遍历整个树:
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
}
该函数的工作原理如下:
- If the object is not a leaf (i.e the object has the children attribute), then:
- 计算每个孩子的深度,保存最大的一个
- 返回 1 + 最深子级的深度
- 否则返回1
js小提琴:http://jsfiddle.net/chrisJamesC/hFTN8/ http://jsfiddle.net/chrisJamesC/hFTN8/
EDIT对于现代 JavaScript,该函数可能如下所示:
const getDepth = ({ children }) => 1 +
(children ? Math.max(...children.map(getDepth)) : 0)
js小提琴:http://jsfiddle.net/chrisJamesC/hFTN8/59/ http://jsfiddle.net/chrisJamesC/hFTN8/59/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)