分层 JSON - 找到 object 的完整路径

Hierarchical JSON - find complete path to an object

我有一个大的 JSON object 用于树源的目的。在这个 JSON 中,我需要找到一个具有给定 ID 的 object 并构建完整的它,这意味着收集它的 parent。为了说明它就像在文件系统中:folde1/folder2/folder3/file.txt。 这是我找到 object:

的递归函数
private find(source, id): string[] {
    for (const key in source)
    {
        var item = source[key];
        if (item.id === id) {
            return this.indexes;
        }                
        
        if (item.children) {
            this.indexes.push(key);
            var subresult = this.find(item.children, id);
            if (subresult) {
                this.indexes.push(key);
                return this.indexes;
            }                    
        }
    }
    return null;
}

我的问题是,在寻找 object 时,我发现了很多错误的 parent,因此结果有额外的数据。

知道它是如何工作的吗?我也想从里面开始寻找路径,但不知道如何得到找到的 object.

的 parent

感谢您的帮助。

我将做一个笼统的回答,希望它适用于您的实际结构。我假设 Tree 看起来像这样:

interface Tree {
  id: string;
  children?: Record<string, Tree>;
}

每个 Tree 都有一个 id 和一个可选的 children 属性,它是 Tree 的字典。 findPathById() 的可能实现如下:

function findPathById(tree: Tree, id: string, curPath: string[] = []): string[] | undefined {
  if (tree.id === id) return curPath;
  const children = tree.children ?? {}
  for (let k in children) {
    const possibleAnswer = findPathById(children[k], id, [...curPath, k]);
    if (possibleAnswer) return possibleAnswer;
  }
  return undefined;
}

这里的方法是该函数采用 一个参数 curPath 对应于当前树节点 的路径,后续路径条目可以附加到该参数。如果此路径被遗漏,则它将被假定为空。如果传入的tree有想要的id,那么我们就找到了,可以returncurPath。否则,我们开始检查 children 的每个 属性(如果存在)以查看 id 是否存在于 children 之一中,在 [=55] 上调用 findPathId =] 值,通过 将 child 键附加到当前路径 创建了一个新的 curPath。如果我们得到结果,我们 return 它。否则,我们继续下一个child。如果我们在检查当前项目并递归向下遍历它的 children 之后还没有找到 id,那么它不在那里,我们 return undefined.


这是一个测试:

const tree: Tree = {
  id: "A",
  children: {
    x: {
      id: "B", children: {
        t: { id: "E" },
        u: { id: "F" }
      }
    },
    y: {
      id: "C", children: {
        v: { id: "G" },
        w: { id: "H" }
      }
    },
    z: { id: "D" }
  }
}

console.log(findPathById(tree, "A")); // []
console.log(findPathById(tree, "D")); // ["z"]
console.log(findPathById(tree, "G")); // ["y", "v"]
console.log(findPathById(tree, "J")); // undefined

这看起来像我们想要的行为。 "A" id 是在根目录下找到的,所以路径是一个空数组。 "D" id 是在 tree.children.z 找到的,所以路径是 ["z"]"G" id 是在 tree.children.y.children.v 找到的,所以路径是 ["y", "v"]。最后,从未找到 "J" id,所以路径是 undefined.


Playground link to code