Javascript构建树层次结构

标签 javascript tree

var array = [{"grandpa","father"}, {"father"}, {"grandpa","father","me"}];

鉴于上面的数组,我想生成一个如下所示的 java 脚本对象 (JSON),它具有类似父子结构的结构。

{"id":"grandpa",
 "children":[
    {"id":"father",
     "children":[
        {"id":"me",
         "children":[]
        }]
    }]
}

最佳答案

如果您要问如何获取层次结构路径列表并创建树结构,那么您可以在 JavaScript 中执行以下操作:

function convertToHierarchy(arry /* array of array of strings */) 
{
    var item, path;

    // Discard duplicates and set up parent/child relationships
    var children = {};
    var hasParent = {};
    for (var i = 0; i < arry.length; i++) 
    {
        var path = arry[i];
        var parent = null;
        for (var j = 0; j < path.length; j++) 
        {
            var item = path[j];
            if (!children[item]) {
                children[item] = {};
            }
            if (parent) {
                children[parent][item] = true; /* dummy value */
                hasParent[item] = true;
            }
            parent = item;
        }
    }

    // Now build the hierarchy
    var result = [];
    for (item in children) {
        if (!hasParent[item]) {
            result.push(buildNodeRecursive(item, children));
        }
    }
    return result;
}

function buildNodeRecursive(item, children)
{
    var node = {id:item, children:[]};
    for (var child in children[item]) {
        node.children.push(buildNodeRecursive(child, children));
    }
    return node;
}

convertToHierarchy([["1","2"], ["1"], ["1","2","3"]]);

编辑:

您的问题仍然不明确。我以前的版本假设了这两件事:

  1. 每个节点ID唯一标识一个节点
  2. 指定的层次结构路径可以从根节点以外的地方开始

在此示例中,我将假设以下内容:

  1. 节点 ID 不是唯一的,但它们在特定节点的子节点中是唯一的
  2. 所有层次结构路径都从树的根节点开始

代码如下:

function convertToHierarchy(arry /* array of array of strings */)
{
    // Build the node structure
    var rootNode = {id:"root", children:{}}
    for (var i = 0; i < arry.length; i++)
    {
        var path = arry[i];
        buildNodeRecursive(rootNode, path, 0);
    }
    return rootNode;
}

function buildNodeRecursive(node, path, idx)
{
    if (idx < path.length)
    {
        item = path[idx];
        if (!node.children[item])
        {
            node.children[item] = {id:item, children:{}};
        }
        buildNodeRecursive(node.children[item], path, idx + 1);
    }
}

返回层次结构,但格式有点不同。但是,您应该了解情况。

关于Javascript构建树层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2286031/

相关文章:

javascript - 无法将数据传递给函数 (jQuery)

python - 给定组件节点和运算符创建树

javascript - 添加元素在html中添加两个位置

javascript - 预编译时未找到 javascript 资源中的路由辅助方法

javascript - Chrome 上的 jQuery fontSize 增加

javascript - 参数后的问号,如 obj.val?.prop

python - 对象与字典 : how to organise a data tree?

php - 在 PHP 中是否有替代数组的数据结构,我可以从中受益于不同的索引技术?

clojure - 如何在 Clojure 中解析异构树

c++ - 二叉树的右 View