Construct tree structure from flat data in JS instead of Python