I am looking to automatically generate a complex Tree structure from a set of objects, with the levels of the tree determined by a list of keys.
For example, my collection could consist of items like
[{a_id: '1', a_name: '1-name', b_id: '2', b_name: '2_name', c_id: '3', c_name: '3_name'}...]
The specified keys for each level of the tree could be something like: ['a', 'b', 'c']
In this setup, the top-level object contains an options
property that holds pairs of {key: any, value: any}
. Each child object also has the same structure, but within an array named groups
, where each group has a group
attribute referring to its parent option's value.
The desired output for the Tree object would resemble:
{
id: 'a',
options: [{ key: '1-name', value: '1'}...],
child: {
id: 'b',
groups: [
{ group: '1', name: '1-name', options: [{key: '2-name', value: '2'}]}
],
child: {
id: 'c',
groups: [
{ group: '2', name: '2-name', options: [{key: '3-name', value: '3'}]}
],
}
}
}
I am struggling to create a concise function that can construct this recursive structure using the basic collection. I aim for the keys to determine the nested relationships and organize the corresponding objects as recursive children. If there is a better approach to transform the original collection into the target structure, I am open to suggestions.