如何获得未知JSON层次结构的总深度
How to get the total depth of an unknown JSON hierarchy?
我一直在努力寻找/构建一个递归函数来解析这个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
}
函数的作用如下:
- 如果对象不是叶子(即对象有children属性),则:
- 计算每个子结点的深度,保存最大的那个
- 返回1 +最深子节点的深度
- 否则,返回1
jsFiddle: http://jsfiddle.net/chrisJamesC/hFTN8/
编辑在现代JavaScript中,这个函数看起来像这样:
const getDepth = ({ children }) => 1 +
(children ? Math.max(...children.map(getDepth)) : 0)
jsFiddle: http://jsfiddle.net/chrisJamesC/hFTN8/59/
这将计算树中"叶子"的数量:
var treeCount = function (branch) {
if (!branch.children) {
return 1;
}
return branch.children.reduce(function (c, b) {
return c + treeCount(b);
}, 0)
}
还有另一种获取深度的方法:
var depthCount = function (branch) {
if (!branch.children) {
return 1;
}
return 1 + d3.max(branch.children.map(depthCount));
}
相关文章:
- 从json对象聚集数据并创建层次结构
- Html5-使用SVG路径绘制的组织层次结构在左手边被剪裁
- 使用jquery为移动布局更改html层次结构
- 如何在javascript中使用2个一维数组创建层次结构树
- 从d3.js中的csv创建树层次结构
- D3:使用 nest 函数将带有父键的平面数据转换为层次结构
- JSON 层次结构,如何获取元素
- 展平多个嵌套层次结构数组-d3.js
- Kendo UI层次结构DataSource架构不工作
- 用于构建树节点层次结构的javascript库
- 如何在JavaScript中显示注释线程层次结构
- js初学者-如何获得网页中所选内容的html以及整个节点层次结构
- Jquery选择层次结构
- 无法通过jQuery查找来定位层次结构中的对象
- Html5画布,继承层次结构可能导致闪烁
- d3.js-通过csv显示饼图中的层次结构
- 如果其他语句层次结构 JS
- 如果我忽略对象在层次结构中的深度,如何为对象的字段赋值
- 如何获得未知JSON层次结构的总深度
- 在平展对象层次结构中设置深度级别属性