Javascript:深入查找树中的对象,然后通过树返回对象及其路径

时间:2015-07-15 12:26:20

标签: javascript tree

我的数据结构看起来像这样:

let tree = {
  id: 1,
  name: "Some Name",
  children: [
    {
      id: 2,
      name: "Child 1",
      children: [...more nested objects...]
    }
  ]
};

我已经编写了一个递归函数来查找该树中的给定对象,但我现在还需要将路径通过树返回给返回的对象。我正试图找出如何修改我的搜索功能来做到这一点。

搜索功能:

_findInTree = (id, tree) => {
    let result;
    if (tree.id === id) {
      result = tree;
    } else {
      for (let child of tree.children) {
        if (child.id === id) { result = child; }
        result = this._findInTree(id, child);
        if (result) { break; }
      }
    }
    return result;
  }

2 个答案:

答案 0 :(得分:1)

所以T.J. Crowders的位置最终出现了记录路径的错误,最后我调整了解决方案以获得以下内容,这非常有效。

  _findInTree(id, tree) {
    if (tree.id === id) {
      let path = [tree.name];
      return {result: tree, path};
    } else {
      for (let child of tree.children) {
        let tmp = this._findInTree(id, child);
        if (!_.isEmpty(tmp)) {
          tmp.path.unshift(tree.name);
          return tmp;
        }
      }
      return {};
    }
  }

答案 1 :(得分:0)

对于我来说,我需要将Kevin Whitaker代码改为此

_findInTree(id, tree) {
    if (tree.id === id) {
      let path = [tree.name];
      return {result: tree, path};
    } else if (tree.children) { //THIS IS THE CHANGES THAT I NEED
      for (let child of tree.children) {
        let tmp = this._findInTree(id, child);
        if (!_.isEmpty(tmp)) {
          tmp.path.unshift(tree.name);
          return tmp;
        }
      }
      return {};
    }
  }