I’m struggling with a specific issue: I have an object structured like this:
Object {
id: string;
parentId: string;
}
What I’m aiming for is a nested object structure like this:
NestedObject {
id: string;
parentId: string;
children: [
{
id: 62,
parentId: 74,
children: [{ id: 56, parentId: 62 }, { id: 63, parentId: 62 }],
}
}
The function I came up with returns a somewhat nested object, but it's not exactly what I need. I’m having trouble pinpointing the issue. Can anyone help me identify where the problem might be? Thank you.
function list_to_tree(arr: any[]) {
const tree = {
root: {
id: "root",
children: []
}
}
arr.forEach(item => {
tree[item.id] = {
...item,
children: []
}
})
Object.values(tree).forEach(item => {
if (item.parentId) {
tree[item.parentId].children.push(item)
const i = tree[item.parentId]
tree.root.children.push(i)
}
})
return tree.root
}