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"])
The only thing he does not do is set the leaves of the tree to zero - he sets them to an empty object. This is normal?
If you want the leaves to be empty, 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 } } }*/
source share