美文网首页
过滤指定深度的树结构数据

过滤指定深度的树结构数据

作者: 小小的开发人员 | 来源:发表于2019-10-05 22:32 被阅读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)
}

相关文章

网友评论

      本文标题:过滤指定深度的树结构数据

      本文链接:https://www.haomeiwen.com/subject/ylvypctx.html