jfk*_*k83 7 javascript json nested d3.js
我一直在努力寻找/构建一个递归函数来解析这个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
}]
}]
}]
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*che 25
您可以使用递归函数遍历整个树:
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
}
Run Code Online (Sandbox Code Playgroud)
该功能的工作原理如下:
jsFiddle:http://jsfiddle.net/chrisJamesC/hFTN8/
编辑 使用现代JavaScript,函数可能如下所示:
const getDepth = ({ children }) => 1 +
(children ? Math.max(...children.map(getDepth)) : 0)
Run Code Online (Sandbox Code Playgroud)
jsFiddle:http://jsfiddle.net/chrisJamesC/hFTN8/59/
归档时间: |
|
查看次数: |
15190 次 |
最近记录: |