I have a 2D array representing a tree in this format:
[["Food", 0], ["Dairy", 1], ["Milk", 2], ["Low-fat", 3], ["Butter", 2], ["Cheese", 2], ["Vegetables", 1], ["Spinach", 2], ["Meat", 1], ["Fish", 2], ["Salmon", 3], ["Poultry", 2]]
Each item (node) is an array where its first element is the name, and the second is the level (depth) of the node.
I need to convert this 2D array to nested JavaScript objects, where each node-object consists of name (string) and children (array of objects). The result should be the root object (here, "Food") with all other items as its children. The input array will always come ordered, so it can be assumed that the first element is root.
What's the best way to go about this, either with iteration or recursion?
MilkandButtergo underDairywith the structure you have.Milk,ButterandCheeseall go underDairy;Spinachis the sole child ofVegetables; etc.Milk,Butter, andCheeseall are of level 2. The last level 1 isDairy, hence their parent.Fishis also a level 2, but comes after the closer level-1Meat. So, in general, a higher level node is a parent of all the nodes with lower levels. The next node with the same level number is its sibling.