I currently have a flat array of objects which I am trying to convert to a nested array of objects. I would like to reuse this function throughout my application - whatever the final depth of the array - so I believe a recursive function would be more appropriate.
My attemps so far I have been a combination of sort + reduce with no success.
It would be much appreciated if you could help me write a clean function for my app !
Initial Array - Flat list of objects
const data = [
{ index: 0, parentKey: '-LLnMWy69vACjys0QIGH', type: 'options', name: 'OPTION_1', key: '-LLnOxg5hsDYR-PcfjBT' },
{ index: 1, parentKey: '-LLnMWy69vACjys0QIGH', type: 'options', name: 'OPTION_2', key: '-LLnP-O6TyHxIpPk9bCU' },
{ index: 0, parentKey: '-LLnLuLt6cn-vBpMWv-u', type: 'collections', name: 'COLLECTION_1', key: '-LLnMWy69vACjys0QIGH' },
{ index: 1, parentKey: '-LLnLuLt6cn-vBpMWv-u', type: 'collections', name: 'COLLECTION_2', key: '-LLnMYNyJmhSCPB-8lL1' },
{ index: 0, name: 'CONFIGURATOR_1', key: '-LLnLuLt6cn-vBpMWv-u' },
{ index: 1, name: 'CONFIGURATOR_2', key: '-LLnLtLs7PjXSAW0PWCQ' },
];
Desired outcome - Nested arrays of objects
const data = [
{
key: '-LLnLuLt6cn-vBpMWv-u',
name: 'CONFIGURATOR_1',
collections: [
{
key: '-LLnMWy69vACjys0QIGH',
name: 'COLLECTION_1',
options: [
{
key: '-LLnOxg5hsDYR-PcfjBT',
name: 'OPTION_1',
},
{
key: '-LLnP-O6TyHxIpPk9bCU',
name: 'OPTION_2',
},
],
},
{
key: '-LLnMYNyJmhSCPB-8lL1',
name: 'COLLECTION_2',
},
],
},
{ key: '-LLnLtLs7PjXSAW0PWCQ',
name: 'CONFIGURATOR_2',
}]