const data=[
{
"name": "A",
"children": [
{
"name": "A1",
"children": [
{
"name": "A11",
"children": null
},
{
"name":"A12",
"children": [
{
"name": "A121",
"children": null
}
]
},
{
"name": "A13",
"children": [
{
"name": "A131",
"children": null
}
]
}
]
},
{
"name": "A2",
"children": [
{
"name": "A21",
"children": null
}]
},
{
"name": "A3",
"children": null
},
{
"name": "A4",
"children": null
}
]
},
{
"name": "B",
"children": [
{
"name":"B1",
"children": null
}
]
},
{
"name": "C",
"children":null
}
];
// 设置每个节点的统计字段,并返回所有节点总数。
var toTreeCount = (data=[], countField='count')=>data.reduce((total,cur)=>(total+(cur[countField] = toTreeCount(cur.children||[], countField))),data.length);
console.log(toTreeCount(data,'childCount'));
console.log(data);
/*
function getLeafCountTree(json) {
if(json.children ==null || json.children.length == 0){
json.colspan = 1;
return 1;
}else{
var leafCount = 0;
for(var i = 0 ; i < json.children.length ; i++){
leafCount = leafCount + getLeafCountTree(json.children[i]);
}
json.colspan = leafCount;
return leafCount;
}
}
console.log(getLeafCountTree(data)) */
console