const map = new Map();
for (const entry of components) {
const parent = map.get(entry.parentId);
if (parent) {
parent.children || (parent.children = []);
parent.children.push(entry);
}
map.set(entry.id, entry);
}
const rootItemId = 1;
console.log(map.get(rootItemId));
function createTree({
data,
key = 'id',
parentKey = 'parentId',
childrenKey = 'children',
}) {
const tree = Object.fromEntries(data.map(n => [
n[key],
{ ...n, [childrenKey]: [] }
]));
return Object.values(tree).filter(n => (
!tree[n[parentKey]]?.[childrenKey].push(n)
));
}
const result = createTree({
data: components,
childrenKey: 'components',
});