Answer the question
In order to leave comments, you need to log in
How to make a tree from a flat array?
There is such a data structure, from the server:
Data goes in order, type: 0 is a group, further down the list are the values of this group (type: 1)
Test = [
{id: 1, type: 0, name: 'Группа 1'},
{id: 2, type: 1, name: 'Элемент группы 1'},
{id: 3, type: 1, name: 'Элемент группы 1'},
{id: 4, type: 1, name: 'Элемент группы 1'},
{id: 5, type: 0, name: 'Группа 2'},
{id: 6, type: 1, name: 'Элемент группы 2'},
{id: 7, type: 1, name: 'Элемент группы 2'},
{id: 8, type: 0, name: 'Группа 3'},
{id: 9, type: 1, name: 'Элемент группы 3'},
];
export interface ITest {
id: number;
type: number;
name: string;
childrens?: ITest[];
}
genForm(data: ITest[]) {
const test: ITest[] = [];
let index = 0;
data.forEach((d, i) => {
if (d.type === 0) {
index = i;
test[index] = d;
test[index].childrens = [];
}
if (d.type === 1) {
test[index].childrens[i] = d;
}
}
});
console.log(test);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question