<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>json-query</title>
<script type="text/javascript">
const arr = [
{
"name": "aaa",
"Children": [
{
"name": "aaa",
"Children": [
{
"name": "ccc",
'type': 'none',
"Children": [
{
"name": "ccc",
"Children": []
}
]
},
{
"name": "eee",
"Children": []
}
]
}
]
}]
</script>
<script type="text/javascript">
function getLeafCountTree(data) {
if (data.Children.length == 0) {
data.colspan = 1;
return 1;
} else {
var leafCount = 0;
for (var i = 0; i < data.Children.length; i++) {
leafCount = leafCount + getLeafCountTree(data.Children[i]);
}
data.colspan = leafCount;
if (data.type === "none") {//特殊节点不计算在内
return leafCount;
} else {
return leafCount + 1;
}
}
}
console.log(getLeafCountTree(arr[0]))
</script>
</head>
<body>
</body>
</html>
效果图:

这篇博客介绍了一个JavaScript函数,用于递归计算具有层级结构的JSON对象中叶子节点的数量。函数`getLeafCountTree`遍历数据,记录每个节点的`colspan`属性,最终返回叶子节点总数。在示例中,展示了如何应用该函数于一个具体的JSON数据结构。
5万+

被折叠的 条评论
为什么被折叠?



