B
B
beta-it2018-03-21 11:34:52
JavaScript
beta-it, 2018-03-21 11:34:52

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'},
];


Directly in Angular I try to make a tree out of this structure:
Interface:
export interface ITest {
  id: number;
        type: number;
  name: string;
  childrens?: ITest[];
}


And directly the function that forms the tree:
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);
  }


Actually, in general, it displays everything as it should, but the terminal throws an error like: error TS2532: Object is possibly 'undefined'.

Question: how to win or build a tree somehow differently?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-21
@beta-it

data.forEach((d) => {
  if (d.type === 0) {
    test.push({ ...d });
    test[test.length - 1].children = [];
  }
  if (d.type === 1) {
    test[test.length - 1].children.push({ ...d });
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question