过滤指定深度的树结构数据
2019-10-05 本文已影响0人
小小的开发人员
背景
element-ui的tree数据结构如下图:

现在只需要2层数据,而不需要之后层级的children对应的数据
解决方案
第一步:
给数据添加个deepth属性,表示当前树结构的深度
function setDataDeepth(sourceData) {
const formatSourceData = {
deepth: 0,
children: _.clone(sourceData),
}
function addDeepth(data) {
if (!data.children) return
data.children.forEach((child) => {
child.deepth = data.deepth + 1
addDeepth(child)
})
}
addDeepth(formatSourceData)
return formatSourceData.children
}
第二步:将大于指定层级的children设置为null
function clearChildrenByDeepth(sourceData, deepth) {
const formatSourceData = {
children: _.clone(sourceData),
}
function filterData(data) {
if (!data.children) return
data.children.forEach((child) => {
if (child.deepth >= deepth) {
child.children = null
} else {
filterData(child)
}
})
}
filterData(formatSourceData)
return formatSourceData.children
}
function filterDataByDeepth(sourceData, deepth) {
return clearChildrenByDeepth(setDataDeepth(sourceData), deepth)
}