@dake1231

Как правильно собрать вложенный объект без указания родителя?

Здравствуйте! Есть дерево в виде массива с указанием уровня вложенности, нужно из него сделать массив с вложенными объектами.
На вход имеется вот такой массив:
[
{id:1, title: 'test1', level:0},
{id:2, title: 'test2', level:1},
{id:3, title: 'test3', level:2},
{id:4, title: 'test4', level:1},
{id:5, title: 'test5', level:0},
]


на выходе должны получить вот такой:
[
{
   id:1,
   title: 'test1',
   nodes: [
      {
          id:2,
          title: 'test2',
         nodes: [
             id: 3,
             title: 'test3'
             nodes: []
        ]
      },
      {
          id:4,
          title: 'test4',
          nodes: []
      }
   ],
   {
       id:5,
       title: 'test5',
       nodes: []
   }
}
]
  • Вопрос задан
  • 284 просмотра
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
function createTree(data, levelKey, childrenKey) {
  const tree = [];

  data.forEach(n => {
    let arr = tree;

    for (let level = 0; n[levelKey] > level++; ) {
      arr = arr[arr.length - 1][childrenKey];
    }

    arr.push(Object.assign({ [childrenKey]: [] }, n));
  });

  return tree;
}


const tree = createTree([
  { id: 1, title: 'test1', level: 0 },
  { id: 2, title: 'test2', level: 1 },
  { id: 3, title: 'test3', level: 2 },
  { id: 4, title: 'test4', level: 1 },
  { id: 5, title: 'test5', level: 0 },
], 'level', 'nodes');
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы