其他分享
首页 > 其他分享> > 递归寻找子节点的所有父节点(父,爷,祖等)

递归寻找子节点的所有父节点(父,爷,祖等)

作者:互联网

let retArr: any = [];
/**
 * 递归找ID
 * @param str 
 * @param arr 
 */
const findPId = (str: any, arr = data as any) => {
  let curPId = str;
  for (var idx in arr) {
    if (arr[idx].id == str) {
      //返回名字
      retArr.push(arr[idx].name);
      curPId = arr[idx].parentId;
      //找到的时候把找到的这个节点的父ID赋给变量,然后从新开始递归树找到该父节点的父节点,依次循环得到结果
      if (arr[idx].children) {
        findPId(curPId, data);
      }
    }
    //没找到的时候正常递归去寻找下面的节点
    if (arr[idx].children) {
      findPId(curPId, arr[idx].children);
    }
  }
  return retArr;
};

const clickHanlder = () => {
  let ret = findPId("ZX5001");
  console.log(ret);
};

HTML:

 <button type="button" @click="clickHanlder">查找</button>

测试数据:

const data = [
  {
    id: "1",
    name: "zs",
    parentId: "0",
    children: [
      {
        id: "1-1",
        name: "zs-1",
        parentId: "1",
        children: [
          {
            id: "1-1-1",
            name: "zs-1-1",
            parentId: "1-1",
            children: [
              {
                id: "ZX5001",
                name: "zs-1-1-1-1",
                parentId: '1-1-1',
                children: [
                  {
                    id: "1-1-1-1-41",
                    name: "zs-1-1-zx",
                    parentId: "ZX5001",
                    children: null,
                  },
                ],
              },
            ],
          },
          {
            id: "1-1-2",
            name: "zs-1-2",
            parentId: "1-1",
            children: [
              { id: "1-1-2-ZX", name: "zs-1-2-1", parentId: 1, children: null },
            ],
          },
        ],
      },
      {
        id:'zxxc',
        name: "zs-2",
        parentId: "1",
        children: [
          {
            id: "2-1-1",
            name: "zs-2-1",
            parentId: "zxxc",
            children: [
              {
                id: "2-1-1-1",
                name: "zs-2-1-1Z",
                parentId: "2-1-1",
                children: [
                  {
                    id: "2-1-1-1-1",
                    name: "zs-2-1-1-1",
                    parentId: "2-1-1-1",
                    children: null,
                  },
                ],
              },
            ],
          },
        ],
      },
    ],
  },
];

 

标签:arr,name,递归,祖等,children,节点,parentId,id,zs
来源: https://www.cnblogs.com/llcdbk/p/16576825.html