Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将数组转换为树?_Javascript_Arrays_Tree - Fatal编程技术网

Javascript 如何将数组转换为树?

Javascript 如何将数组转换为树?,javascript,arrays,tree,Javascript,Arrays,Tree,我有两个数组 ["a", "b", "c"] ["a", "b", "d"] 我想把它转换成 { a : { b : { c : null, d : null } } } 我该怎么做呢?var-tree={} var tree = {} function addToTree(tree, array) { for (var i = 0, length = array

我有两个数组

["a", "b", "c"]
["a", "b", "d"]
我想把它转换成

{
    a :
    {
        b :
        {
            c : null,
            d : null
        }
    }
}
我该怎么做呢?

var-tree={}
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": {}
        }
    }
}*/
函数addToTree(树,数组){ for(var i=0,length=array.length;i
它唯一没有做的就是将树的叶子设置为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
        }
    }
}*/
函数addToTree(树,数组){
for(var i=0,length=array.length;i
YUI的JSON实用程序可能会有所帮助,但我还没有给出答案,因为我无法直接告诉您它是否能满足您的需求。或者,想想看,看看YUI的增强实用程序,它合并了我相信的对象。别忘了使用
var
var I=0,length=array。length
@Marcel Korpel:谢谢,修复了。