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?
Recursion isn’t necessary. I think something like this is what you’re looking for: