Convert array to tree

Can someone explain this code? I do not understand what is inside the structure for.

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": {} } } }*/ 
+6
source share
2 answers

I expanded the body of the for loop and added some comments in an attempt to make things more explicit.

 for (var i = 0, length = array.length; i < length; i++) { // Assign the current item in the array to a variable var current = array[i]; // If there is no property on the "tree" object corresponding to the value of // "current", set this property to a new object if (!tree[current]) { tree[current] = {}; } // Set the "tree" variable to the field in the "tree" object whose // name corresponds to "current". On the next loop iteration, "tree" will // refer to this "child" object, resulting in a tree-like object being // created as we iterate. tree = tree[current]; } 
+1
source

This confuses the external variable with the same name before referring to tree inside the shadow function. But due to the way links work in JavaScript, this still changes the external variable.

Here's what he does, step by step, considering only the first call:

  • A call function with a reference to tree (that is, {} ) and ["a", "b", "c"] as arguments
  • Complete the array.
    • Check if there is a property β€œa” in the tree; if not, create it with the value {}
    • The full tree now looks like { a : {} }
    • Now consider the tree we are working on, tree.a (empty)
    • Check if there is a β€œb” property in the current tree; if not, create it with the value {}
    • The full tree now looks like { a : { b: {} } }
    • Now consider the tree we are working on, tree.ab (empty)
    • Check to see if there is a c property in the current tree; if not, create it with the value {}
    • The full tree now looks like { a : { b: { c: {} } } }
    • Now consider the tree we are working on, tree.abc (empty)
  • End of function
+1
source

All Articles