Looking to transform the given list into a hierarchical structure with nested children fields. The 'parentId' attribute has been omitted for clarity, as it will be used in the transformation process using Ramda's immutable behavior.
const x = [
{
id: 1,
parentId: null,
name: 'Top 1'
},
{
id: 2,
parentId: 1,
name: 'Middle'
},
{
id: 3,
parentId: 2,
name: 'Leaf'
},
{
id: 4,
parentId: null,
name: 'Top 2'
},
];
The desired output:
const result = [
{
id: 1,
name: 'Top 1',
children: [
{
id: 2,
name: 'Middle',
children: [
{
id: 3,
name: 'Leaf',
children: []
}
]
}
]
},
{
id: 4,
name: 'Top 2',
children: []
}
];