const components = [
{
id: 1,
name: 'Box1',
type: 'Box',
props: {},
elements: [],
},
{
id: 2,
name: 'Box2',
type: 'Box',
props: {},
elements: [],
},
{
id: 3,
name: 'Box3',
type: 'Box',
props: {},
elements: [],
},
{
id: 4,
name: 'Box4',
type: 'Box',
props: {},
elements: [],
},
{
id: 5,
name: 'Box5',
type: 'Box',
props: {},
elements: [],
},
]
const structure = [
{
id: 1,
children: [
2,
3,
],
},
{
id: 2,
children: [
4,
],
},
{
id: 3,
children: [
5,
],
},
{
id: 4,
children: [],
},
{
id: 5,
children: [],
},
]
[
{
id: 1,
name: 'Box1',
type: 'Box',
props: {},
elements: [
{
id: 2,
name: 'Box2',
type: 'Box',
props: {},
elements: [
{
id: 4,
name: 'Box4',
type: 'Box',
props: {},
elements: [],
},
],
},
{
id: 3,
name: 'Box3',
type: 'Box',
props: {},
elements: [
{
id: 5,
name: 'Box5',
type: 'Box',
props: {},
elements: [],
},
],
},
],
},
]
const getComponentById = id => components.find(item => item.id === id)
// Просто проходимся по связям и на основе связи добавляем компонент
const model = structure.map(item => {
return {
...getComponentById(item.id),
}
})
function createTree(arr, structure) {
const tree = Object.fromEntries(arr.map(n => [ n.id, { ...n } ]));
const nonRootIds = structure.flatMap(n => n.children);
structure.forEach(n => tree[n.id].elements = n.children.map(m => tree[m]));
return Object.values(tree).filter(n => !nonRootIds.includes(n.id));
}