js获取树形结构的所有子节点和父节点

//获取某节点的所有父节点
let datasource = [
      {
        path: "/nested",
        title: "Nested",
        children: [
          {
            path: "/nested/menu1",
            title: "Menu1",
            children: [
              {
                path: "/nested/menu1/menu1-1",
                title: "Menu1-1"
              },
              {
                path: "/nested/menu1/menu1-2",
                title: "Menu1-2"
              },
              {
                path: "/nested/menu1/menu1-3",
                title: "Menu1-3"
              },
            ]
          },
          {
            path: "/nested/menu2",
            title: "Menu2",
          }
        ]
      }
    ]
    const targetData = {};
    function loops(data = [], parent) {
      return data.map(({ children, title: value }) => {
        const node = {
          value,
          parent
        }
        targetData[value] = node;
        node.children = loops(children, node);
        return
      })
    }

    function getNode(value) {
      let node = [];
      let currentNode = targetData[value];
      node.push(currentNode.value);
      if (currentNode.parent) {
        node = [...getNode(currentNode.parent.value), ...node];
      }
      return node
    }


    loops(datasource)
    //获取父节点
    const target = getNode('Menu1-3')
    console.log(target)
//获取某节点的所有子节点
getChild(nodes, item, arr) {
    for (let el of nodes) {
        if (el.nodeId === item) {
            arr.push(el.nodeId);
            if (el.children) {
                this.childNodesDeep(el.children, arr);
            }
        } else if (el.children) {
            this.getChild(el.children, item, arr);
        }
    }
    return arr;
},
childNodesDeep(nodes, arr) {
    if (nodes)
        nodes.forEach((ele) => {
            arr.push(ele.nodeId);
            if (ele.children) {
                this.childNodesDeep(ele.children, arr);
            }
        });
},

版权声明:本文为m0_59356280原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。