如下数据
let tagsNodes = [
{
tagsId: 'start',
text: '开始',
children: [
{
tagsId: 'filter',
text: '会员筛选',
children: [
{
branchType: 'yesBranch',
tagsId: 'filter',
text: '会员筛选',
children: [
{
branchType: 'yesBranch',
tagsId: 'filter',
text: '会员筛选',
children: [
{
branchType: 'yesBranch',
tagsId: 'sendMessage',
text: '发消息'
},
{
branchType: 'noBranch',
tagsId: 'removeTags',
text: '移除标签'
}
]
},
{
branchType: 'noBranch',
tagsId: 'addTags',
text: '增加标签'
}
]
},
{
branchType: 'noBranch',
tagsId: 'coupon',
text: '优惠券'
}
]
}
]
}
]
想递归得到深度deepLength 如下图
想要的数据 就是增加一个 deepLength
tags = [
{
tagsId: 'start',
text: '开始',
children: [
{
tagsId: 'filter',
text: '会员筛选',
deepLength: 3,
children: [
{
branchType: 'yesBranch',
tagsId: 'filter',
text: '会员筛选',
deepLength: 2,
children: [
{
branchType: 'yesBranch',
tagsId: 'filter',
text: '会员筛选',
deepLength: 1,
children: [
{
branchType: 'yesBranch',
tagsId: 'sendMessage',
text: '发消息'
},
{
branchType: 'noBranch',
tagsId: 'removeTags',
text: '移除标签'
}
]
},
{
branchType: 'noBranch',
tagsId: 'addTags',
text: '增加标签'
}
]
},
{
branchType: 'noBranch',
tagsId: 'coupon',
text: '优惠券'
}
]
}
]
}
]
实现
tagNodesDeepLength(val: TagNodes[], deepLength: number) {
val.forEach((item) => {
// 如果都有条件 则递归深度 + 1
if (item.tagsId === 'filter' && (item.children && item.children.length === 2)) {
deepLength += 1
item.deepLength = deepLength
}
if (item.children && item.children.length) {
this.tagNodesDeepLength(item.children, deepLength)
}
})
}
this.tagNodesDeepLength(val, 0)
这样 得到的数据 第一级是deepLength:1,第二级deepLength:2,第三级 deepLength:3, 和想要的不符 应该第一级是deepLength:3,第二级deepLength:2,第三级 deepLength:1