统计总数
对于带有children的结构性数据,如果是统计总数,我们可以用全部展平的方式,然后拿到展平数组长度即可。
function flatData(arr, newArr: any = []) {
//递归展平数据,统计数量
if (arr && Array.isArray(arr)) {
for (const item of arr) {
if (item.children) {
this.flatData(item.children, newArr);
} else {
newArr.push(item);
}
}
}
}
统计每一级的个数
如果统计每一级的个数,注意要把非叶子节点排除掉。
function getLeafCount(arr, lastItem: any = null) { //累加结果
if (arr && Array.isArray(arr)) {
for (const item of arr) {
if (item.children) {
if (!item.count) {
item.count = 0;
}
item.count += (item.children.filter(v=>v.isLeaf)).length;
if (lastItem && lastItem.count) {
lastItem.count += item.count;
}
this.getLeafCount(item.children, item);
}
}
}
}
网友评论