树形结构已知子节点找父节点

已知 子节点 求父节点
例如 已知 AAA
希望 得到 A-AA-AAA的格式

data3: [{

      id: 1,
      label: '一级 2',
      children: [{
        id: 3,
        label: '二级 2-1',
        children: [{
          id: 4,
          label: '三级 3-1-1'
        }, {
          id: 5,
          label: '三级 3-1-2',
          disabled: true
        }]
      }, {
        id: 2,
        label: '二级 2-2',
        disabled: true,
        children: [{
          id: 6,
          label: '三级 3-2-1'
        }, {
          id: 7,
          label: '三级 3-2-2',
          disabled: true
        }]
      }]
    }],
阅读 13.3k
6 个回答
let find = (array, label) =>{
    let stack = [];
    let going = true;
    
    let walker = (array, label) => {
        array.forEach(item => {
            if (!going) return;
            stack.push(item['label']);
            if (item['label'] === label) {
                going = false;
            } else if (item['children']) {
                walker(item['children'], label);
            } else {
                stack.pop();
            }
        });
        if (going) stack.pop();
    }

    walker(array, label);

    return stack.join('-');
}

console.log(find(data, '三级 3-2-2'))
// 一级 2-二级 2-2-三级 3-2-2

应该是 DFS

修改一下数据结构即可,添加一个父id属性
{id:2,label:'xxx',children:[],parentId:1}

目测lz遇到的问题是树形选择器,某个节点被选中后希望拿到该节点的层级信息,目前找到比较好的方案是拿到数据后遍历一遍,在每一个节点上生成一个levelInfo字段,标识当前层级信息。

[{
    projectid: 110000,
    name: "一级 1",
    levelInfo: "110000"
    children: [{
        projectid: 110100,
        name: "二级 1-1",
        levelInfo: "110000-110100"
        children: [{
            projectid: 110101,
            name: "三级 1-1-1",
            children: null,
            levelInfo: "110000-110100-110101"
        }, {
            projectid: 110102,
            name: "三级 1-1-2",
            children: null,
            levelInfo: "110000-110100-110102"
        }]
    }, {
        projectid: 110200,
        name: "二级 1-2",
        levelInfo: "110000-110200"
        children: [{
            projectid: 110201,
            name: "三级 1-2-1",
            children: null,
            levelInfo: "110000-110200-110201"
        }, {
            projectid: 110202,
            name: "三级 1-2-2",
            children: null,
            levelInfo: "110000-110200-110202"
        }]
    }]
}]
// 生成该结构的函数,希望可以帮到你
function formatTree(arr, levelInfo = '') {
    return arr.map(item => {
        const newParent = levelInfo ? levelInfo + '-' + item.projectid : '' + item.projectid;
        const temp = {
            ...item,
            levelInfo: newParent
        };
        if (item.children) {
            temp.children = formatTree(item.children, newParent);
        }
        return temp;
    })
}
const getParent = (data, target) => {

  const get = (children, target, record = []) => (
    children.reduce((result, { label, children: innerChildren }) => {
      if (label === target) {
        return [...record, target]
      }
      if (innerChildren) {
        return [...result, ...get(innerChildren, target, [...record, label])]
      }
      return result
    }, []))

  return get(data, target).join('-')
}

// 一级 2-二级 2-1-三级 3-1-2
const str = getParent(data, '三级 3-1-2')

上次遇到这个问题,估计和你的一样,问了问后端大神,给我解决了,可是我不知道原理是什么。给你贴出代码,你看看吧。

<script>
    let treeData = [
        {
            id: 1,
            sub: [
                {
                    id: 2,
                    sub: [
                        {
                            id: 12,
                            sub: [
                                {
                                    id: 13
                                },
                                {
                                    id: 14
                                }
                            ]
                        },
                        {
                            id: 3,
                            sub: [
                                {
                                    id: 4,
                                },
                                {
                                    id: 9,
                                    sub: [
                                        {
                                            id: 10,
                                        },
                                        {
                                            id: 11
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            id: 7,
                            sub: [
                                {id: 8},
                            ]
                        }
                    ]
                },
                {
                    id: 5,
                    sub: [
                        {id: 6},
                    ]
                }
            ]
        },
        {
            id: 100
        }
    ]

    let currentId = 10  // 当前id
    let arr = [] // 定义数组,存放当前id的直系父ids
    function getParentsIds(data) {
        for (let i = 0; i < data.length; i++) {
            let temp = data[i]
            if (temp.id == currentId) {
                arr.push(temp.id);
                return 1
            }
            if (temp && temp.sub && temp.sub.length > 0) {
                let t = getParentsIds(temp.sub)
                if (t == 1) {
                    arr.push(temp.id)
                    return 1
                }
            }
        }
    }
    getParentsIds(treeData)
    console.log(arr)

</script>

利用递归,当最后找到当前节点后再一层层返回上来拿到整棵树从当前节点到根节点的id

function findParentArr(targetId) {
  const ids = []
  function getParent(sources) {
    if (Array.isArray(sources)) {
      return sources.find(elm => {
        let rs = getParent(elm)
        if (rs) {
          ids.push(elm.id)
        }
        return rs
      })
    }
    if (sources.id === targetId) {
      return true
    }
    if (Array.isArray(sources.fileDetail)) {
      return getParent(sources.fileDetail)
    }
  }
  getParent(mock)
  return ids
}
let arr = findParentArr(101)
console.log('Result: ', arr) // [101,100,3,1]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题