js 關(guān)于tree結(jié)構(gòu)數(shù)據(jù) 遞歸操作總結(jié)

原始數(shù)據(jù)

節(jié)點(diǎn)的id 和可以確定父子關(guān)系的 parentId

const treeData = [
  {
    id: '1',
    parentId: '',
    name: '紅——水果',
    identity: '紅方'
  },
  {
    id: '1-1',
    name: '紅-水果-紅色的',
    identity: '紅方',
    parentId: '1'
  },
  {
    id: '1-1-1',
    name: '紅-水果-紅色的-蘋果',
    identity: '紅方',
    parentId: '1-1'
  },
  {
    id: '1-2',
    name: '紅-水果-綠色的',
    identity: '紅方',
    parentId: '1'
  },
  {
    id: '1-2-1',
    name: '紅-水果-綠色的-西瓜',
    identity: '紅方',
    parentId: '1-2'
  }
]

listTotree

function buildTree(data, parentId = '') {
  const tree = []
  for (const item of data) {
    if (item.parentId === parentId) {
      const children = buildTree(data, item.id)
      if (children.length) {
        item.children = children
      }
      tree.push(item)
    }
  }
  return tree
}

treeToList

function flattenTree(tree, result = []) {
for (const node of tree) {
  const { id, parentId, children, ...rest } = node
  result.push({ id, parentId, ...rest })
  if (children) {
    flattenTree(children, result)
  }
}
return result
}

const flatData = flattenTree(treeData)
console.log(flatData)

tree結(jié)構(gòu)數(shù)據(jù) 過濾

過濾條件:node節(jié)點(diǎn)中 type!==100|| xslx===2

  const formatTree=(data) => {
    return data.filter(item => {return item.Type!=='100'||item.xslx==='2'}).map(item => {

      item=Object.assign({},{...item})

      if(item.children) item.children=formatTree(item.children)
    })
  }

tree節(jié)點(diǎn) 過濾成扁平數(shù)組

過濾葉子節(jié)點(diǎn)

function findLeafNodes(nodes: ChatTreeOption[], result: ChatTreeOption[]) {
    for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i]
        if (node.isLeaf) {
            result.push(node); // 如果當(dāng)前節(jié)點(diǎn)是葉子節(jié)點(diǎn),則把當(dāng)前節(jié)點(diǎn)的信息存入result列表
        }
        else {
            if (node.children) {
                for (let i = 0; i < node.children.length; i++) {
                    findLeafNodes(node.children, result); // 遞歸調(diào)用子節(jié)點(diǎn),查找所有葉子節(jié)點(diǎn)
                }
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容