I stacked with trivial question but can't find the solution. Any help will be appreciated.
I have an array of obects
[
{
id: 1,
title: 'home',
parent: null,
},
{
id: 2,
title: 'about',
parent: null,
},
{
id: 3,
title: 'team',
parent: 2,
},
{
id: 4,
title: 'company',
parent: 2,
},
,
{
id: 5,
title: 'department',
parent: 4,
},
];
To make Tree I use this function: Solution from here
const treeify = (arr) => {
const tree = [];
const lookup = {};
arr.forEach((o) => {
lookup[o.id] = o;
lookup[o.id].children = [];
});
arr.forEach((o) => {
if (o.parent !== null) {
lookup[o.parent].children.push(o);
} else {
tree.push(o);
}
});
return tree;
};
And finally I have the tree like so:
[
{
"id": 1,
"title": "home",
"parent": null,
"children": []
},
{
"id": 2,
"title": "about",
"parent": null,
"children": [
{
"id": 3,
"title": "team",
"parent": 2,
"children": []
},
{
"id": 4,
"title": "company",
"parent": 2,
"children": [
{
"id": 5,
"title": "department",
"parent": 4,
"children": []
}
]
}
]
}
]
The question is: How replace parent ID with object itself?
I want the result like:
"id": 4,
"title": "company",
"parent": { // <-- how to change just id to object here
"id": 2,
"title": "about",
"parent": null,
},
"children": []
Thank you for help!