JS遍历树形数据

树形数据结构遍历某个key值

深度优先遍历(DFS)

let tree = [{
    id: '1',
    name: '节点1',
    children: [{
        id: '1-1',
        name: '节点1-1'
    }]
}, {
    id: '2',
    name: '节点2',
    children: [{
        id: '2-1',
        name: '节点2-1'
    }, {
        id: '2-2',
        name: '节点2-2',
        children: [{
            id: '2-2-1',
            name: '节点2-2-1'
        }]
    }]
}, {
    id: '3',
    name: '节点3'
}, {
    id: '4',
    name: '节点4'
}]

function treeIterator(tree, func) {
    tree.forEach((node) => {
        func(node)
        node.children && treeIterator(node.children, func)
    })
}

treeIterator(tree, (node) => {
    console.log(node.name)
})

循环实现

function treeIterator(tree, func) {
    let node, curTree = [...tree]
    while ((node = curTree.shift())) {
        func(node)
        node.children && curTree.unshift(...node.children)
    }
}
treeIterator(tree, (node) => {
    console.log(node.name)
})

广度优遍历

function treeIterator(tree, func) {
  let node, curTree = [...tree]
  while ((node = curTree.shift())) {
    func(node)
    node.children && curTree.push(...node.children)
  }
}
treeIterator(tree, (node) => {
  console.log(node.name)
})

posted @ 2022-05-10 21:09  南风晚来晚相识  阅读(1869)  评论(0编辑  收藏  举报