I have an array of objects, where each object has a property (parentsList) indicating the category the current item belongs to, something like:
const data = [
{
...other properties,
"parentsList": [
"Assets",
"Icons"
],
},
{
...other properties,
"parentsList": [
"Assets",
"Fonts"
],
},
{
...other properties,
"parentsList": [
"Programming",
"JavaScript",
"Docs"
],
},
{
...other properties,
"parentsList": [
"Programming",
"JavaScript",
"React",
"Libraries",
],
},
]
That means the first object belongs to assets/icons, the second to assets/fonts, third to programming/javascript/docs and so on.
I'm trying to map it to a tree-like view, where siblings should be under the same parent, something like:
const data = [
{
name: 'Assets',
id: 'assets',
children: [
{
name: 'Icons',
id: 'assets/icons',
},
{
name: 'Illustrations',
id: 'assets/illustrations',
},
],
},
{
name: 'Programming',
id: 'programming',
children: [
{
name: 'JavaScript',
id: 'programming/javascript',
children: [
{
name: 'Docs',
id: 'programming/javascript/docs',
},
{
name: 'React',
id: 'programming/javascript/react',
children: [
{
name: 'Libraries',
id: 'programming/javascript/react/libraries',
},
],
},
],
},
],
},
]
I imagine it's gonna be easier to traverse from the right, maybe with reduceRight(), but I can't seem to get it right.
Anyone would know how to achieve that?
Thanks!