The easiest way to do this, in my opinion, is to read the entire set of records into an array and then build the nested levels from that array, using a recursive function. Probably very similar to how you did it in JS coding.
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.