【问题标题】:Construct hierarchy tree from flat list with children field and preserve the children order?从带有子字段的平面列表构造层次结构树并保留子顺序?
【发布时间】:2019-03-05 04:55:54
【问题描述】:

之前herehere 提出了类似的问题,也有npm-packages 但是 - 我找不到允许的 JavaScript 代码 sn-p 或 npm 包保持孩子的顺序

考虑以下数据结构:

var nodes = [{id: 'a', parent: null, children: ['c', 'b']},
             {id: 'b', parent: 'a', children: []},
             {id: 'c', parent: 'a', children: []}]

我想得到一个这样的嵌套对象:

var tree = {id: 'a', parent: null, children: [
    {id: 'c', parent: 'a', children: []},
    {id: 'b', parent: 'a', children: []}
]}

重要的事实是,由于 a 的孩子的顺序是 c, b,因此嵌套的 children 数组结构将保留顺序。

【问题讨论】:

    标签: javascript arrays tree hierarchy


    【解决方案1】:

    如果你先建立一个地图就很简单了:

     const nodeById = new Map(nodes.map(el => [el.id, el]));
    

    然后你就可以轻松地构建树了:

     let root;
    
     for(const node of nodes) {
       node.children = node.children.map(id => nodeById.get(id));
       if(!node.parent) root = node;
     }
    

    【讨论】:

    • 感谢您的建议。我必须注意到,这种方法改变了原始结构。如果您从事例如,这是非常不幸的。 React 状态对象的属性。是否有可能在无需深度克隆原始结构或增加额外计算复杂度的情况下修改您的代码?
    • 我不想像这样改变 Reacts 的状态。我的目标是根据状态计算派生值。我将深度复制原始节点数组以防止改变状态。不过,我想知道是否有更有效的方法。
    • @karlitos 不是真的,这仍然是 O(n)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2018-02-06
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多