I have a flat array of objects that I need in a (deeply) nested array of objects.
My flat array (IDs are random in reality, but changed here for clarity, and nesting can be very deep):
const tags = [
{
id: 'tag1',
title: 'Tag 1',
childIds: ['tag11', 'tag12'],
root: true
},
{
id: 'tag11',
title: 'Tag 11',
childIds: ['tag111', 'tag112'],
},
{
id: 'tag12',
title: 'Tag 12',
childIds: ['tag121']
},
{
id: 'tag111',
title: 'Tag 111',
childIds: []
},
{
id: 'tag112',
title: 'Tag 112',
childIds: []
},
{
id: 'tag121',
title: 'Tag 121',
childIds: []
}
]
My desired output:
tagsNested = [
{
id: 'tag1',
title: 'Tag 1',
tags: [
{
id: 'tag11',
title: 'tag 11',
tags: [
{
id: 'tag111',
title: 'Tag 111',
tags: []
},
{
id: 'tag112',
title: 'Tag 112',
tags: []
}
]
},
{
id: 'tag12',
title: 'tag 12',
tags: [
{
id: 'tag121',
title: 'Tag 121',
tags: []
}
]
}
]
}
]
My best effort so far keeps nesting all tags under any tag.
I.e. I do get a nested array, but each tags-array contains all tags.
function unflatten(tag, nestedTags) {
if (tag.childIds) {
tag.childIds.forEach((childId) => {
var childTag = tags.find((t) => t.id === childId)
childTag.tags = unflatten(childTag, nestedTags)
nestedTags.push(childTag)
})
}
return nestedTags
}
const rootTag = tags.find((tag) => tag.root)
console.log(unflatten(rootTag, []))
I really struggle with these recursive functions and figuring out how to make the return statements give me the right data.