代码之家  ›  专栏  ›  技术社区  ›  BrunoLM

如何将数组转换为树?

  •  4
  • BrunoLM  · 技术社区  · 14 年前

    ["a", "b", "c"]
    ["a", "b", "d"]
    

    我想把它转换成

    {
        a :
        {
            b :
            {
                c : null,
                d : null
            }
        }
    }
    

    我该怎么做?

    1 回复  |  直到 14 年前
        1
  •  12
  •   Cristian Sanchez    14 年前
    var tree = {}
    
    function addToTree(tree, array) { 
       for (var i = 0, length = array.length; i < length; i++) {
           tree = tree[array[i]] = tree[array[i]] || {}
       }
    }
    
    addToTree(tree, ["a", "b", "c"])
    addToTree(tree, ["a", "b", "d"])
    
    /*{
        "a": {
            "b": {
                "c": {},
                "d": {}
            }
        }
    }*/
    

    它唯一没有做的就是将树的叶子设置为null——它将它们设置为空对象。可以吗?

    如果希望叶为空,则使用以下选项:

    function addToTree(tree, array) { 
        for (var i = 0, length = array.length; i < length; i++) {
            tree = tree[array[i]] = ((i == length - 1) ? null : tree[array[i]] || {})
        }
    }
    
    // or, without the i == length - 1 check in each iteration:
    function addToTree(tree, array) { 
        for (var i = 0, length = array.length; i < length -1; i++) {
            tree = tree[array[i]] = tree[array[i]] || {};
        } 
        tree[array[i]] = null;
    }
    
    /*{
        "a": {
            "b": {
                "c": null,
                "d": null
            }
        }
    }*/