js递归遍历树形,根据id,到他本身以及他所有的直系父辈的id,并且放入一个数组中

解决思路

可以通过递归遍历树形数组结构来实现该需求。具体步骤如下:

1.定义一个空数组 result,用于存放结果。

2.遍历树形数组结构,找到与给定 Id 匹配的节点。

3.将该节点的 Id 加入 result 数组。

4.如果该节点存在父节点,则将其父节点的 Id 加入 result 数组,并递归处理该父节点,直到根节点。

5.最终返回 result 数组。

数据准备

const tree = [
  {
    id: 1,
    name: "Node 1",
    children: [
      {
        id: 2,
        name: "Node 1.1",
        children: [],
      },
      {
        id: 3,
        name: "Node 1.2",
        children: [
          {
            id: 4,
            name: "Node 1.2.1",
            children: [],
          },
          {
            id: 5,
            name: "Node 1.2.2",
            children: [],
          },
        ],
      },
    ],
  },
  {
    id: 6,
    name: "Node 2",
    children: [],
  },
];

代码实现

方式一

function findAncestorsById(tree, id, result = []) {
  for (const node of tree) {
    if (node.id === id) {
      result.push(id);
      return result;
    }
    if (node.children.length) {
      const temp = findAncestorsById(node.children, id, result);
      if (temp) {
        result.push(node.id);
        return result;
      }
    }
  }
  return null;
}

 方式二

function findRegionById(tree, id, parents = []) {
  for (let i = 0; i < tree.length; i++) {
    const region = tree[i];
    if (region.id === id) {
      parents.push(region.id);
      return parents.reverse();
    } else if (region.children) {
      const found = findRegionById(region.children, id, parents);
      if (found) {
        parents.push(region.id);
        return found;
      }
    }
  }
  return null;
}

 方式三

function findNodeAndParentsById(tree, id, parents = []) {
  for (const node of tree) {
    if (node.id === id) {
      return [...parents, node.id];
    }

    if (node.children) {
      const result = findNodeAndParentsById(node.children, id, [
        ...parents,
        node.id,
      ]);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

获取结果

const id = 5;
const result = findNodeAndParentsById(tree, id);
console.log(result, "result++++++++++++++++++");

其中 tree 是树形数组结构,id 是给定的节点 Id,result 是用于存放结果的数组。

函数使用了递归的方式来遍历树形数组结构,并将匹配的节点的 Id 和其父节点的 Id 存入 result 数组中。

最终返回 result 数组。

如果遍历完整个 JSON 数据结构,仍然没有找到指定的节点,函数将返回 null。

猜你喜欢

转载自blog.csdn.net/weixin_43743175/article/details/129731508