Javascript: Relational nested JSON
<p>I've been using <a href="https://github.com/louischatriot/nedb/" rel="nofollow">NeDB</a> as a persistent data storage model in my Electron/Angular application.  The setup of this data works perfectly for the main purpose of my application.  I show everything from table "0" and when the use clicks on an options it takes them to all items from table "1" that have a "foreign" that matches the "key" from the selected item from table "0".  Like any other 1:n relational data.</p>

<p>I want to display the objects in an accordion like fashion for my users to be able to interact with the relationships.  I want to be able to do this recursively, but cannot seem to wrap my head around it.</p>

<p><strong>A chunk from my flat JSON file is this:</strong></p>

<pre><code>{"_id":"000000","type":"dc","table":"0","key":"A","cat":"CAD Assessment","foreign":"A"}
{"_id":"000002","type":"dc","table":"1","key":"1","cat":"Coronary angiography with or without left heart catheterization and left ventriculography","foreign":"A"}
{"_id":"000005","type":"dc","table":"2","key":"1.1","cat":"Suspected or known ACS","foreign":"1"}
{"_id":"000006","type":"dc","table":"2","key":"1.2","cat":"Suspected CAD: No prior noninvasive stress imaging (no prior PCI, CABG, or angiogram showing &gt;=50% angiographic stenosis)","foreign":"1"}
</code></pre>

<p><strong>And I want it to look like this:</strong></p>

<pre><code>{
    "_id":"000000",
    "type":"dc",
    "table":"0",
    "key":"A",
    "cat":"CAD Assessment",
    "foreign": [
        {
            "_id":"000002",
            "type":"dc",
            "table":"1",
            "key":"1",
            "cat":"Coronary angiography with or without left heart catheterization and left ventriculography"
            "foreign": [
                {
                    "_id":"000005",
                    "type":"dc",
                    "table":"2",
                    "key":"1.1",
                    "cat":"Suspected or known ACS",
                    "foreign":"1"
                },
                {
                    "_id":"000006",
                    "type":"dc",
                    "table":"2",
                    "key":"1.2",
                    "cat":"Suspected CAD: No prior noninvasive stress imaging (no prior PCI, CABG, or angiogram showing &gt;=50% angiographic stenosis)",
                    "foreign":"1"
                }
            ]
        }
    ]
}
</code></pre>

<p>Is this even a possible thing?  I'm hoping somebody with a lot more experience can point me in the right direction here.  I'm ready to stop banging my head against the wall.</p>