【问题标题】:trying to recursively create an array of results from a json tree-like structure JavaScript尝试从 json 树状结构 JavaScript 递归地创建结果数组
【发布时间】:2016-09-22 21:44:29
【问题描述】:

我正在尝试获取特定人的后代列表。以下是我目前所拥有的:

function getDescendants(id, descendants){
    children = getChildren(id);
    if(children){
        for (var child in children) {
           if(children.hasOwnProperty(child)){
               descendants.push(getDescendants(children[child].id, descendants));
           }
        }
    }
    return getPersonById(id);
}

这一直有效,直到它返回初始调用并忘记了 children 数组。

getChildren 返回子对象的数组 getPersonById 返回一个人对象

感谢任何帮助/建议

【问题讨论】:

  • 代码不合逻辑,为什么不直接返回descendants
  • @AbdelrhmanMohamed 好吧,想象后代甚至没有传入想象它的全局......如果我们在循环中这样做for (var child in children) { if(children.hasOwnProperty(child)){ descendants.push(children[child]); getDescendants(children[child].id); } }
  • 让我明白这一点,你需要记住第一次调用getChildren 时返回的原始数组吗?您是在尝试制作 b-tree 吗?
  • @ryan 正确...但我并没有尝试制作 b-tree,只是在创建结果数组(后代)时尝试遍历树

标签: javascript recursion data-structures


【解决方案1】:
function getDescendants(id, descendants, originalChildren ){
    children = getChildren(id);
    if(children){
        var originalChildren = originalChildren || children;
        for (var child in children) {
           if(children.hasOwnProperty(child)){
               descendants.push(getDescendants(children[child].id, descendants, originalChildren ));
           }
        }
    }
    return getPersonById(id);
}

当您第一次调用 getDescendants 时,传递 null 或者只是不传递第三个插槽中的任何内容。如果它为空,则它将children 的值存储在变量中,否则它将每次存储originalChildren,并且您将继续通过您的函数传递children 的第一个实例。

【讨论】:

    【解决方案2】:

    在咨询了一些同事和很多脑痛之后,这就是我们想出的。

    let getDescendants = (parentID, people) => {
        return people.filter((el)=>{
            return el.parents.indexOf(parentID) > -1;
        }).map((kid)=>{
            return [...getDescendants(kid.id, people), kid.id ];
        }).reduce((a, b) => {
            return a.concat(b);
        }, []);
    }
    

    谢谢大家的帮助

    【讨论】:

      猜你喜欢
      • 2012-12-14
      • 2019-04-14
      • 2019-12-18
      • 2017-06-01
      • 1970-01-01
      • 2018-07-26
      • 2020-01-19
      • 2012-07-15
      • 2021-04-17
      相关资源
      最近更新 更多