开发者

How to convert array to tree?

开发者 https://www.devze.com 2023-01-15 09:17 出处:网络
I have two arrays [\"a\", \"b\", \"c\"] [\"a\", \"b\", \"d\"] I want to convert it to { a : { b : { c : null, d : null

I have two arrays

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

I want to convert it to

{
    a :
    {
        b :
        {
            c : null,
            d : null
        }
  开发者_运维技巧  }
}

How can I do that?


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": {}
        }
    }
}*/

Only thing it doesn't do is set the leaves of the tree to null -- it sets them to an empty object. Is that ok?

If you want the leaves to be null, then use the following instead:

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
        }
    }
}*/
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号