项目中有一个地方是设计提资树,它是后端直接全部返回提资树的所有节点信息,有多层节点,区分类型字段是nodeType,然而需求是只能在nodeType为“构件”的节点下去点击或勾选进行后续的操作,很明显需要对数据进行扁平化处理,怎么解决呢?这里采用递归==》
如有更好的方法,还请各路大神指点
1、数据结构(节点的nodeType并不一致,存在提资节点下仍然挂载提资节点,这种情况下就更不可能用单一的if层层判断了)
data: [{
label: '一级 1',
nodeType: '提资父节点'
children: [{
label: '二级 1-1',
nodeType: '提资节点'
children: [{
label: '三级 1-1-1',
nodeType: '构件'
}]
}]
}, {
label: '一级 2',
nodeType: '提资节点'
children: [{
label: '二级 2-1',
nodeType: '提资节点'
children: [{
label: '三级 2-1-1',
nodeType: '构件'
}]
}, {
label: '二级 2-2',
nodeType: '提资节点'
children: [{
label: '三级 2-2-1'
nodeType: '构件'
}]
}]
}, {
label: '一级 3',
nodeType: '提资父节点'
children: [{
label: '二级 3-1',
nodeType: '提资节点'
children: [{
label: '三级 3-1-1',
nodeType: '构件'
}]
}, {
label: '二级 3-2',
nodeType: '提资节点'
children: [{
label: '三级 3-2-1',
nodeType: '构件'
}]
}]
}],
2、递归方法
methods:{
getGouJianIds(list){
for(let i = 0; i < list.length; i++){
if(list[i].nodeType == '构件'){
this.goujianList.push(list[i])
}
if(list[i].children && list[i].children.length > 0){
this.getGouJianIds(list[i].children)
}
}
}
}