【问题标题】:Javascript building tree hierarchyJavascript构建树层次结构
【发布时间】:2010-02-18 03:07:02
【问题描述】:
var array = [{"grandpa","father"}, {"father"}, {"grandpa","father","me"}];

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

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

【问题讨论】:

  • 根据数组生成javascript对象
  • 如果您不能清楚地表达问题,我们将很难帮助您解决它。你在尝试解码 JSON 吗?
  • “[B]基于数组”:在什么意义上?输入与输出有何关系?
  • 数组仍然是无效的语法。
  • 给出更好的描述。不要使用这么多相同的数字,这让我们很难分辨什么是什么。尝试使用明确的词而不是数字。甚至可能是具有自然层次结构的词,例如水果 => 苹果、橙子。提供一个有效的 JavaScript 数组。

标签: javascript tree


【解决方案1】:

如果您要问如何获取层次结构路径列表并创建树结构,以下是您可以在 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);
    }
}

返回层次结构,但格式有点不同。但是,您应该得到图片。

【讨论】:

  • 是的,我正在寻找这个。我测试过,但是 convertToHierarchy 返回空的孩子。
  • 糟糕,忘记了 for..in 不适用于数组。已验证它适用于我的编辑。
  • 好吧,实际上我需要对重复项的支持。比如,convertToHierarchy([["1","2"], ["1"], ["1","1","2"]]);所以我们不能用item作为hash的key,
【解决方案2】:

我认为这应该可行。我正在使用 firebug 来跟踪输出的结构。

    var el =  {"name": "Level 1", "paths" : ["fruits"]};
    var el2 = {"name": "Level 3", "paths" : ["fruits", "apples", "fuji"]};
    var el3 = {"name": "Level 4", "paths" : ["fruits", "apples", "fuji", "red"]};
    var el4 = {"name": "Level 2", "paths" : ["fruits", "apples"]};

    var allEl = [el, el2, el3, el4];


    /* Define recursive function for setting the child */
    function setChild(parent, pos, arr, name)
    {
        if(pos < arr.length)
        {
            if(pos == arr.length-1) //last element of the paths
                parent.name = name;

            if(!parent.children){
                parent.children = [];
                parent.children[0] = new Object();
            }
            setChild(parent.children[0], pos + 1, arr, name);
        }
    }

    /* Test starts here */
    var root = new Object();

    for(var i=0; i<allEl.length; i++)
    {
        var el = allEl[i];
        setChild(root, 0, el.paths, el.name);
    }

    //Firefox debugging ...getfirebug.com
    console.debug(root);

【讨论】:

  • 嗯,对同级节点无效.. var arr = ["fruits"]; var arr2 = [“水果”、“苹果”、“富士”]; var arr3 = [“水果”,“苹果”]; var arr4 = [“水果”、“苹果”、“富士”、“红色”]; var arr5 = [“水果”、“苹果”、“富士”、“绿色”];
【解决方案3】:

如果您想对 JSON 进行编码,只需使用 JSON 库即可。

不要尝试自己动手。

【讨论】:

  • 阅读问题 - 他不是在尝试对 JSON 数据进行编码,而是在尝试从平面数据结构构建一棵树。
猜你喜欢
  • 2015-12-05
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多